"""
Management command to test HIS connection.

Usage:
    python manage.py test_his_connection [--config ID]

Options:
    --config ID  Test specific configuration by ID
"""
from django.core.management.base import BaseCommand

from apps.integrations.models import IntegrationConfig, SourceSystem
from apps.integrations.services.his_client import HISClient


class Command(BaseCommand):
    help = 'Test connectivity to HIS system'

    def add_arguments(self, parser):
        parser.add_argument(
            '--config',
            type=str,
            help='Configuration ID or name to test (optional)'
        )
        parser.add_argument(
            '--all',
            action='store_true',
            help='Test all active configurations'
        )

    def handle(self, *args, **options):
        config_id = options.get('config')
        test_all = options.get('all')

        self.stdout.write(self.style.MIGRATE_HEADING('=' * 70))
        self.stdout.write(self.style.MIGRATE_HEADING('HIS Connection Test'))
        self.stdout.write(self.style.MIGRATE_HEADING('=' * 70))

        configs = []
        
        if config_id:
            # Try to find by ID first, then by name
            config = IntegrationConfig.objects.filter(
                id=config_id,
                source_system=SourceSystem.HIS
            ).first()
            
            if not config:
                config = IntegrationConfig.objects.filter(
                    name__icontains=config_id,
                    source_system=SourceSystem.HIS
                ).first()
            
            if config:
                configs = [config]
            else:
                self.stdout.write(
                    self.style.ERROR(f'Configuration "{config_id}" not found')
                )
                return
        
        elif test_all:
            configs = list(IntegrationConfig.objects.filter(
                source_system=SourceSystem.HIS,
                is_active=True
            ))
        
        else:
            # Test default (first active)
            config = IntegrationConfig.objects.filter(
                source_system=SourceSystem.HIS,
                is_active=True
            ).first()
            
            if config:
                configs = [config]
            else:
                # Try with no config (fallback)
                self.stdout.write(
                    self.style.WARNING('No active HIS configurations found. Testing fallback...')
                )
                configs = [None]
        
        if not configs:
            self.stdout.write(
                self.style.ERROR('No configurations to test')
            )
            return
        
        all_passed = True
        
        for config in configs:
            if config:
                self.stdout.write(
                    self.style.MIGRATE_HEADING(f'\n📡 Testing: {config.name}')
                )
                self.stdout.write(f'   API URL: {config.api_url or "Not set"}')
                self.stdout.write(f'   API Key: {"✓ Set" if config.api_key else "✗ Not set"}')
                client = HISClient(config)
            else:
                self.stdout.write(
                    self.style.MIGRATE_HEADING('\n📡 Testing: Fallback (no config)')
                )
                client = HISClient()
            
            self.stdout.write('   Connecting...', ending=' ')
            
            result = client.test_connection()
            
            if result['success']:
                self.stdout.write(self.style.SUCCESS('✓ Success'))
                self.stdout.write(f'   Message: {result["message"]}')
            else:
                self.stdout.write(self.style.ERROR('✗ Failed'))
                self.stdout.write(f'   Error: {result["message"]}')
                all_passed = False
        
        self.stdout.write(self.style.MIGRATE_HEADING('\n' + '=' * 70))
        
        if all_passed:
            self.stdout.write(self.style.SUCCESS('All connection tests passed!'))
        else:
            self.stdout.write(self.style.ERROR('Some connection tests failed'))
