"""Agent endpoint registry for Chanakya.

This is the single source of truth for every sub-agent's network location,
display name, and description.  Both the agents (for ``to_a2a`` registration
and uvicorn startup) and Chanakya (for A2A client URLs) derive their values
from here — no more scattered hardcoded strings.

Usage::

    from backend.chanakya.config import AGENT_REGISTRY

    cfg = AGENT_REGISTRY["gmail"]
    print(cfg.url)          # http://localhost:8001
    print(cfg.name)         # Gmail Agent
    print(cfg.module_path)  # backend.chanakya.gmail.agent:app
"""

from __future__ import annotations

import os
from dataclasses import dataclass, field


@dataclass(frozen=True)
class AgentEndpointConfig:
    """Configuration for a single A2A sub-agent."""

    # Unique key used to look up this agent in AGENT_REGISTRY
    key: str

    # Human-readable display name exposed in A2A registration
    name: str

    # Short description exposed in A2A registration
    description: str

    # Uvicorn module:app path, used when the agent is run as __main__
    module_path: str

    # Network location — override via environment variables at deploy time
    host: str = "localhost"
    port: int = 8000
    # Set True for agents that expose a structured POST /query endpoint
    supports_query: bool = False

    @property
    def url(self) -> str:
        """Full base URL for the A2A client."""
        return f"http://{self.host}:{self.port}"

    @property
    def chat_url(self) -> str:
        """URL for the pylogue chat UI (mounted at /chat on the same port)."""
        return f"http://{self.host}:{self.port}/chat"


def _port(env_var: str, default: int) -> int:
    """Read an integer port from an environment variable with a fallback."""
    raw = os.environ.get(env_var)
    if raw:
        try:
            return int(raw)
        except ValueError:
            pass
    return default


# ---------------------------------------------------------------------------
# Registry — add new agents here; nothing else needs changing.
# ---------------------------------------------------------------------------

AGENT_REGISTRY: dict[str, AgentEndpointConfig] = {
    "gmail": AgentEndpointConfig(
        key="gmail",
        name="Gmail Agent",
        description=(
            "Searches and retrieves emails from Tata Steel's Gmail. "
            "Covers procurement, operations, safety, and project communications."
        ),
        module_path="backend.chanakya.gmail.agent:app",
        host=os.environ.get("GMAIL_AGENT_HOST", "localhost"),
        port=_port("GMAIL_AGENT_PORT", 8001),
    ),
    "jira": AgentEndpointConfig(
        key="jira",
        name="Jira Agent",
        description=(
            "Searches and retrieves Jira tickets for Tata Steel operations. "
            "Covers maintenance, procurement, safety, and Enterprise Brain development."
        ),
        module_path="backend.chanakya.jira.agent:app",
        host=os.environ.get("JIRA_AGENT_HOST", "localhost"),
        port=_port("JIRA_AGENT_PORT", 8002),
    ),
    "user_aware": AgentEndpointConfig(
        key="user_aware",
        name="User Aware Agent",
        description=(
            "Delivers a personalised org snapshot to a user based on their role and project membership. "
            "Filters emails and tickets from the daily snapshot and shapes the response to their persona."
        ),
        module_path="backend.chanakya.user_aware.agent:app",
        host=os.environ.get("USER_AWARE_AGENT_HOST", "localhost"),
        port=_port("USER_AWARE_AGENT_PORT", 8003),
    ),
    "insurance": AgentEndpointConfig(
        key="insurance",
        name="Insurance Agent",
        description=(
            "Answers natural-language questions by querying a live PostgreSQL database. "
            "Reads the schema definition, generates accurate SELECT queries, and returns results."
        ),
        module_path="backend.chanakya.insurance.agent:app",
        host=os.environ.get("POSTGRES_AGENT_HOST", "localhost"),
        port=_port("POSTGRES_AGENT_PORT", 8004),
        supports_query=False,  # Disabled — service not started
    ),
    "tatasteel": AgentEndpointConfig(
        key="tatasteel",
        name="Tatasteel Agent",
        description=(
            "Answers natural-language questions about Tata Steel's construction project database. "
            "Covers contracts, early warnings, compensation events, and quotations."
        ),
        module_path="backend.chanakya.tatasteel.server:app",
        host=os.environ.get("TATASTEEL_AGENT_HOST", "localhost"),
        port=_port("TATASTEEL_AGENT_PORT", 8005),
        supports_query=True,
    ),
    # "infinithesim": AgentEndpointConfig(
    #     key="infinithesim",
    #     name="Infinithesim Agent",
    #     description=(
    #         "Answers natural-language questions about Infinithesim's HDB program database. "
    #         "Covers seekers, registrations, program allocations, attendance, and participant analytics "
    #         "for program_id 38."
    #     ),
    #     module_path="backend.chanakya.infinithesim.agent:app",
    #     host=os.environ.get("INFINITHESIM_AGENT_HOST", "localhost"),
    #     port=_port("INFINITHESIM_AGENT_PORT", 8006),
    #     supports_query=True,
    # ),
    "chanakya": AgentEndpointConfig(
        key="chanakya",
        name="Chanakya",
        description=(
            "Central intelligence hub for Tata Steel's Enterprise Brain. "
            "Orchestrates Gmail, Jira, and Insurance agents to answer cross-system questions."
        ),
        module_path="backend.chanakya.rt_agent:app",
        host=os.environ.get("CHANAKYA_HOST", "localhost"),
        port=_port("CHANAKYA_PORT", 8010),
    ),
    "ui_agent": AgentEndpointConfig(
        key="ui_agent",
        name="UI Agent",
        description=(
            "Receives raw query rows and a plain-text explanation from a data agent "
            "and renders them as frontend-ready visualisation widgets."
        ),
        module_path="backend.chanakya.ui_agent.agent:app",
        host=os.environ.get("UI_AGENT_HOST", "localhost"),
        port=_port("UI_AGENT_PORT", 8011),
    ),
}
