"""
Management command to mark staff as physicians based on existing ratings.

This command scans all PhysicianIndividualRating records and marks
the associated Staff records as physicians.

Usage:
    python manage.py mark_physicians_from_ratings [--hospital_id <uuid>]
"""
from django.core.management.base import BaseCommand
from django.db import transaction

from apps.organizations.models import Staff
from apps.physicians.models import PhysicianIndividualRating


class Command(BaseCommand):
    help = 'Mark staff as physicians based on existing physician ratings'

    def add_arguments(self, parser):
        parser.add_argument(
            '--hospital_id',
            type=str,
            help='Optional hospital ID to limit the update to a specific hospital',
            required=False
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be updated without making changes',
        )

    def handle(self, *args, **options):
        dry_run = options['dry_run']
        hospital_id = options.get('hospital_id')

        # Get all staff IDs that have physician ratings
        ratings_query = PhysicianIndividualRating.objects.filter(
            staff__isnull=False
        )
        
        if hospital_id:
            ratings_query = ratings_query.filter(hospital_id=hospital_id)
            self.stdout.write(f"Filtering by hospital_id: {hospital_id}")

        # Get unique staff IDs from ratings
        staff_ids = list(ratings_query.values_list('staff_id', flat=True).distinct())
        
        self.stdout.write(f"Found {len(staff_ids)} staff members with physician ratings")

        if not staff_ids:
            self.stdout.write(self.style.WARNING("No staff with physician ratings found"))
            return

        # Find staff that are not yet marked as physicians
        staff_to_update = Staff.objects.filter(
            id__in=staff_ids,
            physician=False
        )

        count = staff_to_update.count()
        
        if count == 0:
            self.stdout.write(self.style.SUCCESS("All staff with physician ratings are already marked as physicians"))
            return

        self.stdout.write(f"Will update {count} staff records to mark as physicians")

        if dry_run:
            self.stdout.write(self.style.WARNING("DRY RUN - No changes made"))
            for staff in staff_to_update[:10]:
                self.stdout.write(f"  Would update: {staff.get_full_name()} (ID: {staff.id})")
            if count > 10:
                self.stdout.write(f"  ... and {count - 10} more")
            return

        # Update the staff records
        with transaction.atomic():
            updated = staff_to_update.update(physician=True)

        self.stdout.write(self.style.SUCCESS(f"Successfully updated {updated} staff records as physicians"))
