"""Build `AgentCard` instances for LangGraph-backed agents."""

from __future__ import annotations

from urllib.parse import urljoin

from a2a.types import AgentCapabilities, AgentCard, AgentSkill

from a2a_langgraph.config import A2ALangGraphConfig


def _normalize_mount_path(mount_path: str) -> str:
    p = mount_path.strip()
    if not p.startswith("/"):
        p = "/" + p
    return p.rstrip("/") or "/"


def join_public_agent_url(base_url: str, mount_path: str) -> str:
    """Return an absolute URL for the agent's primary JSON-RPC endpoint root."""
    base = base_url.rstrip("/") + "/"
    path = _normalize_mount_path(mount_path).lstrip("/")
    return urljoin(base, path)


def build_agent_card(config: A2ALangGraphConfig, mount_path: str) -> AgentCard:
    """Construct an `AgentCard` with defaults suitable for a LangGraph workflow."""
    skills: list[AgentSkill] = config.skills or [
        AgentSkill(
            id="langgraph",
            name=config.agent_name,
            description=config.agent_description,
            tags=["langgraph"],
        )
    ]
    capabilities = config.capabilities or AgentCapabilities()

    return AgentCard(
        name=config.agent_name,
        description=config.agent_description,
        version=config.version,
        protocol_version=config.protocol_version,
        url=join_public_agent_url(config.base_url, mount_path),
        preferred_transport="JSONRPC",
        default_input_modes=list(config.default_input_modes),
        default_output_modes=list(config.default_output_modes),
        skills=skills,
        capabilities=capabilities,
        security=config.security,
        security_schemes=config.security_schemes,
    )
