#!/usr/bin/env python
"""
Test script to demonstrate AI-PX Action integration for complaints.

This script tests:
1. Creating a complaint triggers AI analysis
2. AI analysis creates PX Action when hospital has auto_create enabled
3. The action_id is returned in the task result
4. The complaint and action are properly linked
"""
import os
import sys
import django

# Setup Django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
django.setup()

from apps.complaints.models import Complaint, ComplaintCategory
from apps.organizations.models import Hospital, Patient, Department
from apps.accounts.models import User
from apps.px_action_center.models import PXAction
from apps.complaints.tasks import analyze_complaint_with_ai
from django.contrib.contenttypes.models import ContentType


def test_ai_creates_px_action():
    """Test that AI analysis creates PX Action when enabled"""
    
    print("=" * 80)
    print("TEST: AI Analysis Creates PX Action Integration")
    print("=" * 80)
    print()
    
    # Get or create test data
    try:
        hospital = Hospital.objects.first()
        if not hospital:
            print("❌ No hospital found. Please create test data first.")
            return False
        
        patient = Patient.objects.filter(hospital=hospital).first()
        if not patient:
            print("❌ No patient found. Please create test data first.")
            return False
        
        category = ComplaintCategory.objects.filter(hospital=hospital).first()
        if not category:
            category = ComplaintCategory.objects.create(
                hospital=hospital,
                name_en="Service Quality",
                name_ar="جودة الخدمة",
                code="service_quality",
                description="Issues related to service quality"
            )
            print(f"✓ Created test category: {category.name_en}")
        
        # Enable auto-create for this hospital
        hospital_metadata = hospital.metadata or {}
        hospital_metadata['auto_create_action_on_complaint'] = True
        hospital.metadata = hospital_metadata
        hospital.save()
        print(f"✓ Enabled auto-create PX Action for hospital: {hospital.name}")
        
    except Exception as e:
        print(f"❌ Error setting up test data: {str(e)}")
        return False
    
    print()
    
    # Create a test complaint
    print("Step 1: Creating test complaint...")
    try:
        complaint = Complaint.objects.create(
            hospital=hospital,
            patient=patient,
            category=category,
            title="Test Complaint for AI Integration",
            description="I had a very poor experience at the hospital. The staff was rude and unhelpful. I waited for 2 hours to see a doctor.",
            source="api",
            severity="medium",
            priority="medium",
            status="open"
        )
        print(f"✓ Created complaint #{complaint.id}")
        print(f"  Title: {complaint.title}")
        print(f"  Severity: {complaint.severity}")
        print(f"  Priority: {complaint.priority}")
    except Exception as e:
        print(f"❌ Error creating complaint: {str(e)}")
        return False
    
    print()
    
    # Run AI analysis task
    print("Step 2: Running AI analysis task...")
    try:
        result = analyze_complaint_with_ai(str(complaint.id))
        
        print(f"✓ AI analysis task completed")
        print(f"  Status: {result.get('status')}")
        
        if result.get('status') == 'success':
            print(f"  Severity (AI): {result.get('severity')}")
            print(f"  Priority (AI): {result.get('priority')}")
            print(f"  Category (AI): {result.get('category')}")
            print(f"  Department (AI): {result.get('department')}")
            
            # Check if PX Action was created
            action_id = result.get('px_action_id')
            if action_id:
                print(f"  PX Action ID: {action_id}")
                print(f"  Auto-created: {result.get('px_action_auto_created')}")
            else:
                print(f"  ⚠️  No PX Action created (auto-create may be disabled)")
        else:
            print(f"  ❌ AI analysis failed: {result.get('reason')}")
            return False
            
    except Exception as e:
        print(f"❌ Error running AI analysis: {str(e)}")
        import traceback
        traceback.print_exc()
        return False
    
    print()
    
    # Verify complaint was updated
    print("Step 3: Verifying complaint updates...")
    complaint.refresh_from_db()
    
    print(f"✓ Complaint refreshed from database")
    print(f"  Current Severity: {complaint.severity}")
    print(f"  Current Priority: {complaint.priority}")
    print(f"  Current Category: {complaint.category.name_en if complaint.category else None}")
    print(f"  Current Department: {complaint.department.name if complaint.department else None}")
    print(f"  SLA Due Date: {complaint.due_at}")
    
    # Check AI analysis metadata
    ai_analysis = complaint.metadata.get('ai_analysis', {})
    if ai_analysis:
        print(f"  AI Analysis Metadata: ✓")
        print(f"    - Emotion: {ai_analysis.get('emotion')}")
        print(f"    - Emotion Intensity: {ai_analysis.get('emotion_intensity')}")
        print(f"    - Staff Matches: {ai_analysis.get('staff_match_count', 0)}")
    
    print()
    
    # Verify PX Action was created (if applicable)
    if action_id:
        print("Step 4: Verifying PX Action...")
        try:
            action = PXAction.objects.get(id=action_id)
            
            print(f"✓ PX Action found")
            print(f"  Action ID: {action.id}")
            print(f"  Title: {action.title}")
            print(f"  Category: {action.category}")
            print(f"  Priority: {action.priority}")
            print(f"  Severity: {action.severity}")
            print(f"  Status: {action.status}")
            print(f"  Source Type: {action.source_type}")
            
            # Verify linkage
            complaint_ct = ContentType.objects.get_for_model(Complaint)
            if action.content_type == complaint_ct and action.object_id == complaint.id:
                print(f"  ✓ Action linked to complaint #{complaint.id}")
            else:
                print(f"  ❌ Action NOT linked to complaint")
            
            # Check metadata
            if action.metadata.get('ai_generated'):
                print(f"  ✓ AI Generated: True")
            if action.metadata.get('auto_created'):
                print(f"  ✓ Auto Created: True")
            
        except PXAction.DoesNotExist:
            print(f"❌ PX Action not found in database")
            return False
        except Exception as e:
            print(f"❌ Error verifying PX Action: {str(e)}")
            return False
    else:
        print("Step 4: PX Action not created (auto-create disabled)")
        print("  Note: Enable hospital.metadata.auto_create_action_on_complaint to test")
    
    print()
    print("=" * 80)
    print("✓ TEST COMPLETED SUCCESSFULLY")
    print("=" * 80)
    
    return True


def test_manual_action_creation():
    """Test manual PX Action creation via API endpoint"""
    
    print()
    print("=" * 80)
    print("TEST: Manual PX Action Creation (via API)")
    print("=" * 80)
    print()
    print("Note: This test would require an authenticated API request.")
    print("The endpoint is: POST /api/complaints/{id}/create_action_from_ai/")
    print()
    print("This allows PX Admins to manually trigger AI-powered action creation")
    print("even if auto-create is disabled for the hospital.")
    print()


if __name__ == '__main__':
    print("\n" + "=" * 80)
    print(" AI-PX Action Integration Test Suite")
    print("=" * 80)
    print()
    
    success = test_ai_creates_px_action()
    
    if success:
        test_manual_action_creation()
        print("\n✓ All tests passed!")
        sys.exit(0)
    else:
        print("\n❌ Tests failed!")
        sys.exit(1)
