import os
import logging
import json

from pathlib import Path

import asyncio
from a2a.types import AgentCard
from agent.planner import AbiPlannerAgent
from abi_core.common.a2a_server import start_server
from abi_core.common.agent_card_init import init_agent_card_on_startup

logger = logging.getLogger(__name__)

# Get agent card path from environment or use default
agent_card_path = os.getenv('AGENT_CARD', './agent_cards/planner_agent.json')

# Initialize agent card with auth fields on startup
init_agent_card_on_startup(agent_card_path)

def planner_factory(agent_card_path: str):
    """Create Planner agent instance from agent card"""
    if not agent_card_path:
        raise ValueError("AGENT_CARD environment variable not set")
    
    card_path = Path(agent_card_path)
    if not card_path.exists():
        raise FileNotFoundError(f"Agent card not found at: {agent_card_path}")
    
    with card_path.open() as file:
        data = json.load(file)
        agent_card = AgentCard(**data)
    
    if agent_card.name.strip() != "Planner Agent":
        logger.error(f'[!] Unexpected AgentCard name: {agent_card.name!r}')
        raise ValueError(f"Unexpected agent_card name: {agent_card.name!r}")
    
    return AbiPlannerAgent()


if __name__ == "__main__":
    
    logger.info(f"Starting planner with agent_card_path: {agent_card_path}")
    
    # Create the agent instance using the factory
    try:
        agent_instance = planner_factory(agent_card_path)
        logger.info(f"Created agent instance: {type(agent_instance)} - {agent_instance}")
        logger.info(f"Agent has agent_name: {hasattr(agent_instance, 'agent_name')}")
        if hasattr(agent_instance, 'agent_name'):
            logger.info(f"Agent name: {agent_instance.agent_name}")
    except Exception as e:
        logger.error(f"Failed to create agent instance: {e}")
        raise
    
    start_server("0.0.0.0", 11437, agent_card_path, agent_instance)
