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

import os
import json
from pathlib import Path

from a2a.types import AgentCard
from planner import AbiPlannerAgent
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/planner_agent.json')
HOST = os.getenv('AGENT_HOST', '0.0.0.0')
PORT = int(os.getenv('AGENT_PORT', '11437'))


def planner_factory(agent_card_path: str) -> AbiPlannerAgent:
    """
    Factory function to create Planner instance
    
    Args:
        agent_card_path: Path to the agent card JSON file
        
    Returns:
        AbiPlannerAgent: 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 = "Planner 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 = AbiPlannerAgent()
        abi_logging(f'[🚀] Planner agent initialized successfully')
        
        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 Planner agent: {e}')
        raise


def main():
    """Main entry point for Planner agent"""
    
    abi_logging(f'[🌟] Starting Planner 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 = planner_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('[🛑] Planner agent stopped by user')
        return 0
    except Exception as e:
        abi_logging(f'[💥] Fatal error starting Planner agent: {e}')
        return 1


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