"""Django management command: ``python manage.py start_mcp``

Starts the embedded TLS Analyzer MCP server on stdio transport.
IMPORTANT: All log output goes to stderr (stdout is the MCP protocol transport).
"""
import os
import sys

from django.core.management.base import BaseCommand, CommandError


class Command(BaseCommand):
    help = 'Start the embedded TLS Analyzer MCP server on stdio transport'

    def handle(self, *args, **options):
        # Ensure Django is fully initialised before importing server code
        import django
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tianxuan.settings')
        django.setup()

        # CRITICAL: MCP uses stdio for protocol transport.
        # All log messages MUST go to stderr, NOT stdout.
        print('Starting TLS Analyzer MCP server...', file=sys.stderr)
        print('Transport: stdio', file=sys.stderr)
        sys.stderr.flush()

        try:
            from analysis.mcp_server import TLSAnalyzerMCPServer
            server = TLSAnalyzerMCPServer()
            server.run_sync()
        except KeyboardInterrupt:
            print('\nMCP server stopped.', file=sys.stderr)
        except Exception as e:
            raise CommandError(f'MCP server failed: {e}') from e
