"""
Test script for PX Action creation from complaints using AI service.

This script tests the AI-powered PX Action creation feature.
"""
import os
import django
import sys

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

from apps.complaints.models import Complaint
from apps.core.ai_service import AIService
from apps.px_action_center.models import PXAction
from apps.accounts.models import User


def test_ai_service():
    """Test the AI service method directly"""
    print("=" * 80)
    print("TEST 1: AI Service - create_px_action_from_complaint()")
    print("=" * 80)
    
    # Get a sample complaint
    complaint = Complaint.objects.first()
    
    if not complaint:
        print("❌ No complaints found in database. Please seed complaints first.")
        return False
    
    print(f"\nUsing Complaint:")
    print(f"  ID: {complaint.id}")
    print(f"  Title: {complaint.title}")
    print(f"  Description: {complaint.description[:100]}...")
    print(f"  Category: {complaint.category.name_en if complaint.category else 'N/A'}")
    print(f"  Severity: {complaint.severity}")
    print(f"  Priority: {complaint.priority}")
    
    try:
        # Call AI service
        print("\n🔄 Calling AI service to generate action data...")
        action_data = AIService.create_px_action_from_complaint(complaint)
        
        print("\n✅ AI Service Response:")
        print(f"  Title: {action_data['title']}")
        print(f"  Description: {action_data['description'][:100]}...")
        print(f"  Category: {action_data['category']}")
        print(f"  Priority: {action_data['priority']}")
        print(f"  Severity: {action_data['severity']}")
        print(f"  Reasoning: {action_data['reasoning']}")
        
        return action_data
    except Exception as e:
        print(f"\n❌ AI Service Error: {e}")
        import traceback
        traceback.print_exc()
        return None


def test_px_action_creation(action_data, complaint):
    """Test creating a PX Action from the generated data"""
    print("\n" + "=" * 80)
    print("TEST 2: PX Action Creation")
    print("=" * 80)
    
    try:
        from django.contrib.contenttypes.models import ContentType
        
        # Get content type
        complaint_content_type = ContentType.objects.get_for_model(Complaint)
        
        # Create PX Action
        print("\n🔄 Creating PX Action...")
        action = PXAction.objects.create(
            source_type='complaint',
            content_type=complaint_content_type,
            object_id=complaint.id,
            title=action_data['title'],
            description=action_data['description'],
            hospital=complaint.hospital,
            department=complaint.department,
            category=action_data['category'],
            priority=action_data['priority'],
            severity=action_data['severity'],
            assigned_to=None,
            status='open',
            metadata={
                'source_complaint_id': str(complaint.id),
                'source_complaint_title': complaint.title,
                'ai_generated': True,
                'ai_reasoning': action_data.get('reasoning', ''),
                'created_from_ai_suggestion': True
            }
        )
        
        print("\n✅ PX Action Created:")
        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"  Hospital: {action.hospital.name}")
        print(f"  Department: {action.department.name if action.department else 'N/A'}")
        
        return action
    except Exception as e:
        print(f"\n❌ PX Action Creation Error: {e}")
        import traceback
        traceback.print_exc()
        return None


def test_api_endpoint():
    """Test the API endpoint for creating PX Actions"""
    print("\n" + "=" * 80)
    print("TEST 3: API Endpoint - /api/complaints/{id}/create_action_from_ai/")
    print("=" * 80)
    
    # Get a test complaint
    complaint = Complaint.objects.first()
    
    if not complaint:
        print("❌ No complaints found in database.")
        return False
    
    print(f"\nUsing Complaint ID: {complaint.id}")
    
    # Get a PX Admin user for testing
    user = User.objects.filter(groups__name='PX Admin').first()
    
    if not user:
        print("❌ No PX Admin user found. Creating test user...")
        from django.contrib.auth.models import Group
        px_admin_group, _ = Group.objects.get_or_create(name='PX Admin')
        user = User.objects.create_user(
            username='test_px_admin',
            email='test@example.com',
            first_name='Test',
            last_name='Admin'
        )
        user.groups.add(px_admin_group)
        user.hospital = complaint.hospital
        user.save()
        print(f"✅ Created test PX Admin: {user.email}")
    
    try:
        from rest_framework.test import APIRequestFactory
        from apps.complaints.views import ComplaintViewSet
        
        # Create a mock request
        factory = APIRequestFactory()
        request = factory.post(f'/api/complaints/{complaint.id}/create_action_from_ai/')
        request.user = user
        
        # Create viewset instance
        viewset = ComplaintViewSet()
        viewset.kwargs = {'pk': str(complaint.id)}
        viewset.request = request
        viewset.format_kwarg = None
        
        # Call the action
        print("\n🔄 Calling API endpoint...")
        response = viewset.create_action_from_ai(request, pk=complaint.id)
        
        if response.status_code == 201:
            print("\n✅ API Endpoint Success!")
            print(f"  Response Status: {response.status_code}")
            print(f"  Response Data: {response.data}")
            return True
        else:
            print(f"\n❌ API Endpoint Failed:")
            print(f"  Status Code: {response.status_code}")
            print(f"  Response: {response.data}")
            return False
            
    except Exception as e:
        print(f"\n❌ API Endpoint Error: {e}")
        import traceback
        traceback.print_exc()
        return False


def main():
    """Run all tests"""
    print("\n" + "=" * 80)
    print("PX ACTION AI CREATION TEST SUITE")
    print("=" * 80)
    
    # Test 1: AI Service
    action_data = test_ai_service()
    if not action_data:
        print("\n❌ Cannot continue with other tests without AI service working.")
        return
    
    # Test 2: PX Action Creation
    complaint = Complaint.objects.first()
    action = test_px_action_creation(action_data, complaint)
    if not action:
        print("\n❌ PX Action creation failed.")
    else:
        print(f"\n✅ PX Action created successfully! Action ID: {action.id}")
    
    # Test 3: API Endpoint
    api_success = test_api_endpoint()
    if api_success:
        print("\n✅ API endpoint working correctly!")
    else:
        print("\n❌ API endpoint test failed.")
    
    # Summary
    print("\n" + "=" * 80)
    print("TEST SUMMARY")
    print("=" * 80)
    print(f"✅ AI Service: {'PASS' if action_data else 'FAIL'}")
    print(f"✅ PX Action Creation: {'PASS' if action else 'FAIL'}")
    print(f"✅ API Endpoint: {'PASS' if api_success else 'FAIL'}")
    print("=" * 80)
    
    if action_data and action and api_success:
        print("\n🎉 All tests passed! PX Action AI creation is working correctly.")
    else:
        print("\n⚠️  Some tests failed. Please review the errors above.")


if __name__ == '__main__':
    main()
