#!/usr/bin/env python3
"""
Orchestrator Agent Main Entry Point
"""

import os
import json
import threading
import uvicorn
from pathlib import Path

import asyncio
from a2a.types import AgentCard
from orchestrator import AbiOrchestratorAgent
from web_interface import OrchestratorWebinterface
from abi_core.common.a2a_server import start_server
from abi_core.common.utils import abi_logging

# Configuration
AGENT_CARD_PATH = os.getenv('AGENT_CARD', './agent_cards/orchestrator_agent.json')
HOST = os.getenv('AGENT_HOST', '0.0.0.0')
PORT = int(os.getenv('AGENT_PORT', '8002'))

def orchestrator_factory(agent_card_path: str) -> AbiOrchestratorAgent:
    """
    Factory function to create Orchestrator instance
    
    Args:
        agent_card_path: Path to the agent card JSON file
        
    Returns:
        AbiOrchestratorAgent: Configured agent instance
    """
    try:
        # Load agent card
        with Path(agent_card_path).open() as file:
            data = json.load(file)
            agent_card = AgentCard(**data)
        
        # Validate agent card
        expected_name = "Abi Orchestrator Agent"
        if agent_card.name != expected_name:
            abi_logging(f'[!] Unexpected AgentCard name: {agent_card.name!r}')
            abi_logging(f'[!] Expected: {expected_name!r}')
            raise ValueError(f"Unexpected AgentCard name: {agent_card.name!r}")
        
        abi_logging(f'[✅] Agent card loaded: {agent_card.name}')
        abi_logging(f'[📋] Description: {agent_card.description}')
        
        # Create and return new agent instance
        agent_instance = AbiOrchestratorAgent()
        abi_logging(f'[🚀] Orchestrator agent initialized successfully')
        
        # Start web interface in separate thread
        web_port = int(os.getenv('WEB_INTERFACE_PORT', '8083'))
        
        def start_web_server_interface():
            web_interface = OrchestratorWebinterface(agent_instance)
            abi_logging(f'[🌐] Starting Orchestrator Web Server at 0.0.0.0:{web_port}')
            uvicorn.run(
                web_interface.app, 
                host="0.0.0.0", 
                port=web_port,
                log_level="info"
            )

        web_thread = threading.Thread(target=start_web_server_interface, daemon=True)
        web_thread.start()
        abi_logging(f'[✅] Orchestrator web interface started on port {web_port}')
        
        return agent_instance
        
    except FileNotFoundError:
        abi_logging(f'[❌] Agent card file not found: {agent_card_path}')
        raise
    except json.JSONDecodeError as e:
        abi_logging(f'[❌] Invalid JSON in agent card: {e}')
        raise
    except Exception as e:
        abi_logging(f'[❌] Error creating Orchestrator agent: {e}')
        raise


def main():
    """Main entry point for Orchestrator agent"""
    
    abi_logging(f'[🌟] Starting Orchestrator Agent Server')
    abi_logging(f'[🌐] Host: {HOST}')
    abi_logging(f'[🔌] Port: {PORT}')
    abi_logging(f'[📄] Agent Card: {AGENT_CARD_PATH}')
    
    try:
        # Verify agent card exists
        if not Path(AGENT_CARD_PATH).exists():
            abi_logging(f'[❌] Agent card not found: {AGENT_CARD_PATH}')
            abi_logging('[💡] Make sure to create an agent card JSON file')
            return 1
        
        agent = orchestrator_factory(AGENT_CARD_PATH)
        
        # Start the A2A server
        start_server(
            host=HOST,
            port=PORT,
            agent_card=AGENT_CARD_PATH,
            agent=agent
        )
        
    except KeyboardInterrupt:
        abi_logging('[🛑] Orchestrator agent stopped by user')
        return 0
    except Exception as e:
        abi_logging(f'[💥] Fatal error starting Orchestrator agent: {e}')
        return 1


if __name__ == '__main__':
    exit(main())
