"""
Management command to set up HIS integration configuration.

Usage:
    python manage.py setup_his_integration --name "HIS Production" --url "https://his.hospital.com/api"

Options:
    --name       Configuration name
    --url        HIS API URL
    --api-key    API key for authentication
    --hospital   Hospital ID to associate with this config
"""
from django.core.management.base import BaseCommand

from apps.integrations.models import IntegrationConfig, SourceSystem
from apps.organizations.models import Hospital


class Command(BaseCommand):
    help = 'Set up HIS integration configuration'

    def add_arguments(self, parser):
        parser.add_argument(
            '--name',
            type=str,
            required=True,
            help='Configuration name (e.g., "HIS Production")'
        )
        parser.add_argument(
            '--url',
            type=str,
            required=True,
            help='HIS API URL (e.g., "https://his.hospital.com/api/patients")'
        )
        parser.add_argument(
            '--api-key',
            type=str,
            help='API key for authentication'
        )
        parser.add_argument(
            '--hospital',
            type=str,
            help='Hospital code to associate with this config'
        )
        parser.add_argument(
            '--active',
            action='store_true',
            default=True,
            help='Set configuration as active (default: True)'
        )
        parser.add_argument(
            '--force',
            action='store_true',
            help='Update existing configuration with same name'
        )

    def handle(self, *args, **options):
        name = options['name']
        url = options['url']
        api_key = options.get('api_key')
        hospital_code = options.get('hospital')
        is_active = options['active']
        force = options.get('force')

        self.stdout.write(self.style.MIGRATE_HEADING('=' * 70))
        self.stdout.write(self.style.MIGRATE_HEADING('HIS Integration Setup'))
        self.stdout.write(self.style.MIGRATE_HEADING('=' * 70))
        
        # Check for existing configuration
        existing = IntegrationConfig.objects.filter(name=name).first()
        
        if existing and not force:
            self.stdout.write(
                self.style.ERROR(f'Configuration "{name}" already exists. Use --force to update.')
            )
            return
        
        # Build config JSON
        config_json = {}
        
        if hospital_code:
            hospital = Hospital.objects.filter(code=hospital_code).first()
            if hospital:
                config_json['hospital_id'] = str(hospital.id)
                config_json['hospital_code'] = hospital_code
                self.stdout.write(f'Associated with hospital: {hospital.name}')
            else:
                self.stdout.write(
                    self.style.WARNING(f'Hospital with code "{hospital_code}" not found')
                )
        
        # Create or update configuration
        if existing:
            existing.api_url = url
            if api_key:
                existing.api_key = api_key
            existing.is_active = is_active
            existing.config_json.update(config_json)
            existing.save()
            config = existing
            action = 'Updated'
        else:
            config = IntegrationConfig.objects.create(
                name=name,
                source_system=SourceSystem.HIS,
                api_url=url,
                api_key=api_key or '',
                is_active=is_active,
                config_json=config_json
            )
            action = 'Created'
        
        self.stdout.write(self.style.SUCCESS(f'\n✓ {action} configuration:'))
        self.stdout.write(f'   Name: {config.name}')
        self.stdout.write(f'   Source: {config.get_source_system_display()}')
        self.stdout.write(f'   API URL: {config.api_url}')
        self.stdout.write(f'   API Key: {"✓ Set" if config.api_key else "✗ Not set"}')
        self.stdout.write(f'   Active: {"Yes" if config.is_active else "No"}')
        
        self.stdout.write(self.style.MIGRATE_HEADING('\n' + '=' * 70))
        self.stdout.write('Next steps:')
        self.stdout.write('1. Test the connection:')
        self.stdout.write(f'   python manage.py test_his_connection --config "{config.name}"')
        self.stdout.write('2. Manually fetch surveys:')
        self.stdout.write('   python manage.py fetch_his_surveys --test')
        self.stdout.write('3. The automated task will run every 5 minutes via Celery Beat')
        self.stdout.write('=' * 70)
