"""
Management command to sync complaint_type field from AI metadata.

This command updates the complaint_type model field for complaints
that have AI analysis stored in metadata but the model field
hasn't been updated yet.

Usage:
    python manage.py sync_complaint_types [--dry-run] [--hospital-id HOSPITAL_ID]
"""
from django.core.management.base import BaseCommand
from django.db.models import Q


class Command(BaseCommand):
    help = 'Sync complaint_type field from AI metadata'

    def add_arguments(self, parser):
        parser.add_argument(
            '--dry-run',
            action='store_true',
            dest='dry_run',
            help='Show what would be updated without making changes',
        )
        parser.add_argument(
            '--hospital-id',
            type=str,
            dest='hospital_id',
            help='Only sync complaints for a specific hospital',
        )

    def handle(self, *args, **options):
        from apps.complaints.models import Complaint

        dry_run = options.get('dry_run', False)
        hospital_id = options.get('hospital_id')

        self.stdout.write(self.style.WARNING('Starting complaint_type sync...'))

        # Build query for complaints that need syncing
        queryset = Complaint.objects.filter(
            Q(metadata__ai_analysis__complaint_type__isnull=False) &
            (
                Q(complaint_type='complaint') |  # Default value
                Q(complaint_type__isnull=False)
            )
        )

        # Filter by hospital if specified
        if hospital_id:
            queryset = queryset.filter(hospital_id=hospital_id)
            self.stdout.write(f"Filtering by hospital_id: {hospital_id}")

        # Count total
        total = queryset.count()
        self.stdout.write(f"Found {total} complaints to check")

        if total == 0:
            self.stdout.write(self.style.SUCCESS('No complaints need syncing'))
            return

        # Process complaints
        updated = 0
        skipped = 0
        errors = 0

        for complaint in queryset:
            try:
                ai_type = complaint.metadata.get('ai_analysis', {}).get('complaint_type', 'complaint')

                # Check if model field differs from metadata
                if complaint.complaint_type != ai_type:
                    if dry_run:
                        self.stdout.write(
                            f"Would update complaint {complaint.id}: "
                            f"'{complaint.complaint_type}' -> '{ai_type}'"
                        )
                    else:
                        # Update the complaint_type field
                        complaint.complaint_type = ai_type
                        complaint.save(update_fields=['complaint_type'])
                        self.stdout.write(
                            f"Updated complaint {complaint.id}: "
                            f"'{complaint.complaint_type}' -> '{ai_type}'"
                        )
                    updated += 1
                else:
                    skipped += 1

            except Exception as e:
                self.stdout.write(
                    self.style.ERROR(f"Error processing complaint {complaint.id}: {str(e)}")
                )
                errors += 1

        # Summary
        self.stdout.write('\n' + '=' * 60)
        self.stdout.write(self.style.SUCCESS('Sync Complete'))
        self.stdout.write('=' * 60)
        self.stdout.write(f"Total complaints checked: {total}")
        self.stdout.write(f"Updated: {updated}")
        self.stdout.write(f"Skipped (already in sync): {skipped}")
        self.stdout.write(f"Errors: {errors}")
        
        if dry_run:
            self.stdout.write('\n' + self.style.WARNING('DRY RUN - No changes were made'))
        else:
            self.stdout.write(f"\n{self.style.SUCCESS(f'Successfully updated {updated} complaint(s)')}")

        # Show breakdown by type
        if updated > 0 and not dry_run:
            self.stdout.write('\n' + '=' * 60)
            self.stdout.write('Updated Complaints by Type:')
            self.stdout.write('=' * 60)
            
            type_counts = {}
            queryset = Complaint.objects.filter(
                Q(metadata__ai_analysis__complaint_type__isnull=False) &
                Q(hospital_id=hospital_id) if hospital_id else Q()
            )
            
            for complaint in queryset:
                ai_type = complaint.metadata.get('ai_analysis', {}).get('complaint_type', 'complaint')
                if complaint.complaint_type == ai_type:
                    type_counts[ai_type] = type_counts.get(ai_type, 0) + 1
            
            for complaint_type, count in sorted(type_counts.items()):
                self.stdout.write(f"  {complaint_type}: {count}")
