#!/usr/bin/env python3
"""
{{ agent_name }} Agent Main Entry Point
Generated by ABI-Core scaffolding
"""

import os
import json
{% if with_web_interface %}
import threading
import uvicorn
{% endif %}
from pathlib import Path

from a2a.types import AgentCard
from {{ agent_file_name }} import {{ agent_class_name }}
{% if with_web_interface %}
from web_interface import AgentWebInterface
{% endif %}
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/{{ agent_name }}_agent.json')
HOST = os.getenv('AGENT_HOST', '0.0.0.0')
PORT = int(os.getenv('AGENT_PORT', '{{ agent_port | default('8000') }}'))

def {{ agent_name }}_factory(agent_card_path: str) -> {{ agent_class_name }}:
    """
    Factory function to create {{ agent_name }} instance
    
    Args:
        agent_card_path: Path to the agent card JSON file
        
    Returns:
        {{ agent_class_name }}: 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 = "{{ agent_display_name | default(agent_name.title().replace('_', ' ')) }}"
        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}')
        abi_logging(f'[🔧] Capabilities: {", ".join(agent_card.skills[1].tags) if hasattr(agent_card, "skills") else "No skills dumb agent"}')
        
        # Create and return new agent instance
        agent_instance = {{ agent_class_name }}()
        abi_logging(f'[🚀] {{ agent_name }} agent initialized successfully')
        
        {% if with_web_interface %}
        # Start web interface in separate thread
        def start_web_server_interface():
            web_interface = AgentWebInterface(
                agent_instance, 
                interface_name="{{ agent_display_name }} Web Interface"
            )
            abi_logging(f'[🌐] Starting {{ agent_display_name }} Web Server at 0.0.0.0:{{ web_interface_port }}')
            uvicorn.run(
                web_interface.app, 
                host="0.0.0.0", 
                port={{ web_interface_port }},
                log_level="info"
            )

        web_thread = threading.Thread(target=start_web_server_interface, daemon=True)
        web_thread.start()
        abi_logging(f'[✅] {{ agent_display_name }} web interface started on port {{ web_interface_port }}')
        {% endif %}
        
        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 {{ agent_name }} agent: {e}')
        raise

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

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