"""
Management command to create a default organization and assign orphaned hospitals
"""
from django.core.management.base import BaseCommand
from django.db import transaction
from django.utils.translation import gettext_lazy as _

from apps.organizations.models import Organization, Hospital


class Command(BaseCommand):
    help = 'Create a default organization and assign hospitals without organization'

    def add_arguments(self, parser):
        parser.add_argument(
            '--name',
            type=str,
            default='Default Healthcare Organization',
            help='Name of the default organization to create'
        )
        parser.add_argument(
            '--code',
            type=str,
            default='DEFAULT',
            help='Code of the default organization'
        )
        parser.add_argument(
            '--force',
            action='store_true',
            help='Force reassignment even if hospital already has an organization'
        )
        parser.add_argument(
            '--dry-run',
            action='store_true',
            help='Show what would be done without making changes'
        )

    def handle(self, *args, **options):
        name = options['name']
        code = options['code']
        force = options['force']
        dry_run = options['dry_run']

        self.stdout.write(f"\n{'='*60}")
        self.stdout.write(f"Organization Assignment Script")
        self.stdout.write(f"{'='*60}\n")

        with transaction.atomic():
            # Get or create default organization
            org, created = Organization.objects.get_or_create(
                code=code,
                defaults={
                    'name': name,
                    'name_ar': name,  # Use same name for Arabic
                    'status': 'active'
                }
            )

            if created:
                self.stdout.write(
                    self.style.SUCCESS(f"✓ Created organization: {org.name} ({org.code})")
                )
            else:
                self.stdout.write(
                    self.style.SUCCESS(f"✓ Found existing organization: {org.name} ({org.code})")
                )

            # Find hospitals without organization
            if force:
                hospitals_to_assign = Hospital.objects.all()
                self.stdout.write(
                    self.style.WARNING(f"\nForce mode: Will assign ALL hospitals")
                )
            else:
                hospitals_to_assign = Hospital.objects.filter(organization__isnull=True)
                count = hospitals_to_assign.count()
                self.stdout.write(
                    self.style.SUCCESS(f"\nFound {count} hospitals without organization")
                )

            if not hospitals_to_assign.exists():
                self.stdout.write(
                    self.style.SUCCESS("\n✓ All hospitals already have organizations assigned")
                )
                return

            # Display hospitals to be assigned
            self.stdout.write("\nHospitals to assign:")
            for i, hospital in enumerate(hospitals_to_assign, 1):
                org_name = hospital.organization.name if hospital.organization else "None"
                self.stdout.write(
                    f"  {i}. {hospital.name} (Code: {hospital.code}) - Current: {org_name}"
                )

            if dry_run:
                self.stdout.write("\n" + "="*60)
                self.stdout.write(
                    self.style.WARNING("DRY RUN: No changes were made")
                )
                self.stdout.write("="*60 + "\n")
                return

            # Confirm assignment
            if not force:
                confirm = input(f"\nAssign {hospitals_to_assign.count()} hospital(s) to '{org.name}'? (yes/no): ")
                if confirm.lower() not in ['yes', 'y']:
                    self.stdout.write(self.style.ERROR("\n✓ Operation cancelled"))
                    return

            # Assign hospitals to organization
            count = hospitals_to_assign.update(organization=org)
            self.stdout.write(
                self.style.SUCCESS(f"\n✓ Successfully assigned {count} hospital(s) to '{org.name}'")
            )

            # Summary
            self.stdout.write("\n" + "="*60)
            self.stdout.write("Summary:")
            self.stdout.write(f"  Organization: {org.name} ({org.code})")
            self.stdout.write(f"  Hospitals assigned: {count}")
            self.stdout.write(f"  Total hospitals in organization: {org.hospitals.count()}")
            self.stdout.write("="*60 + "\n")

        if dry_run:
            self.stdout.write(self.style.WARNING("\nDry run completed - no changes applied\n"))
        else:
            self.stdout.write(self.style.SUCCESS("\nOrganization assignment completed successfully!\n"))
