"""A2A (Agent2Agent Protocol) v1.0 agent card for the P2HS agent-access surface.

The card describes exactly the operations `src/domain/agent_access/tools.py`
already implements and exposes over MCP — same grants, same scopes, same Core
operations, same idempotent request_key/get_operation polling contract. A2A
gets its own OAuth `resource` (see agent_a2a_url in src/config.py) so its
tokens are audience-bound separately from MCP's, per RFC 8707.

The JSON-RPC endpoint this card advertises (`url`) is hosted on Dashboard —
Core's own hostname is never published. See P2HS-Dash/server/routes/a2a.post.ts,
which translates message/send, tasks/get, and tasks/cancel into the same
POST /api/agent-access/{capabilities,tools} calls the MCP Worker makes.
"""

from __future__ import annotations

AGENT_CARD_PATH = "/.well-known/agent-card.json"

_SCOPE_DESCRIPTIONS = {
    "projects.read": "List and inspect projects and builds in the authorizing workspace.",
    "projects.create": "Create new projects in the authorizing workspace.",
    "builds.run": "Submit AI codegen builds against existing credits.",
    "billing.read": "List current credit package prices.",
    "credits.checkout": "Create a human checkout link to buy credits.",
    "credits.purchase": "Charge the workspace owner's saved card within an owner-approved cap.",
}

_SKILLS = [
    {
        "id": "list_projects",
        "name": "List projects",
        "description": "List projects accessible to this workspace grant.",
        "tags": ["projects", "read"],
        "examples": ["List my P2HS projects"],
    },
    {
        "id": "get_project",
        "name": "Get project",
        "description": "Get the status of an accessible P2HS project.",
        "tags": ["projects", "read"],
        "examples": ["What is the status of project <id>?"],
    },
    {
        "id": "list_builds",
        "name": "List builds",
        "description": "List build statuses for an accessible P2HS project.",
        "tags": ["builds", "read"],
        "examples": ["List builds for project <id>"],
    },
    {
        "id": "get_build",
        "name": "Get build",
        "description": "Get build progress, the result summary, required configuration metadata when blocked, and the dashboard link to review its result and preview. Values are never returned.",
        "tags": ["builds", "read"],
        "examples": ["What is the status of build <run_id>?"],
    },
    {
        "id": "estimate_build",
        "name": "Estimate build",
        "description": "Estimate credits for a build prompt before submitting it. This is an estimate; actual execution determines billing.",
        "tags": ["builds", "read", "billing"],
        "examples": ["Estimate the credit cost of this build prompt"],
    },
    {
        "id": "create_project",
        "name": "Create project",
        "description": (
            "Create a P2HS project. Reuse the same request_key when retrying; "
            "poll get_operation for completion. The new project becomes accessible to this grant."
        ),
        "tags": ["projects", "write"],
        "examples": ["Create a new nuxt_app project named 'Storefront'"],
    },
    {
        "id": "start_build",
        "name": "Start build",
        "description": (
            "Queue a website/app build using existing P2HS credits. Reuse request_key on "
            "retries; never reuse it for a different prompt. Poll get_operation then get_build."
        ),
        "tags": ["builds", "write"],
        "examples": ["Build a booking page for project <id>"],
    },
    {
        "id": "get_operation",
        "name": "Get operation",
        "description": "Get the result of an operation submitted by this grant. Poll no more than once every 10 seconds.",
        "tags": ["operations", "read"],
        "examples": ["Check the result of request_key <key>"],
    },
    {
        "id": "list_credit_packages",
        "name": "List credit packages",
        "description": "List current P2HS credit packages and exact prices in minor currency units.",
        "tags": ["billing", "read"],
        "examples": ["What credit packages are available?"],
    },
    {
        "id": "create_credit_checkout",
        "name": "Create credit checkout link",
        "description": "Create a Stripe checkout link for a person to purchase P2HS credits. Supply the current catalog price and poll get_operation for the link.",
        "tags": ["billing", "write"],
        "examples": ["Create a checkout link for the 'growth' credit package"],
    },
    {
        "id": "purchase_credits",
        "name": "Purchase credits",
        "description": "Buy credits using the owner-approved saved-card spending cap. This charges real money. Supply the current catalog price, reuse request_key on retries, and poll get_operation.",
        "tags": ["billing", "write", "consequential"],
        "examples": ["Buy the 'growth' credit package using the saved card"],
    },
]


def build_agent_card(origin: str, *, a2a_url: str) -> dict:
    """Build the A2A AgentCard. Only mounted while agent_access_enabled (see main.py)."""
    public = origin.rstrip("/")
    a2a = a2a_url.rstrip("/")
    token_url = f"{public}/api/agent-access/token"
    return {
        "protocolVersion": "1.0",
        "name": "P2HS",
        "description": (
            "Build and inspect P2HS websites and apps: list and create projects, submit and "
            "check builds, and — with explicit owner consent and spending caps — buy credits."
        ),
        "url": a2a,
        "preferredTransport": "JSONRPC",
        "version": "0.1.0",
        "provider": {"organization": "P2HS", "url": "https://p2hs.com"},
        "iconUrl": "https://p2hs.com/images/p2hs-logo.png",
        "documentationUrl": f"{public}/auth.md",
        "capabilities": {
            "streaming": False,
            "pushNotifications": False,
            "stateTransitionHistory": True,
        },
        "defaultInputModes": ["application/json"],
        "defaultOutputModes": ["application/json", "text/plain"],
        "securitySchemes": {
            "p2hsOAuth": {
                "type": "oauth2",
                "description": (
                    "Authorization code + S256 PKCE for a delegated user, or client_credentials "
                    "for a workspace service account. resource must be exactly this agent card's url. "
                    "See documentationUrl."
                ),
                "flows": {
                    "authorizationCode": {
                        "authorizationUrl": f"{public}/agents/authorize",
                        "tokenUrl": token_url,
                        "refreshUrl": token_url,
                        "scopes": dict(_SCOPE_DESCRIPTIONS),
                    },
                    "clientCredentials": {
                        "tokenUrl": token_url,
                        "scopes": dict(_SCOPE_DESCRIPTIONS),
                    },
                },
            }
        },
        "security": [{"p2hsOAuth": ["projects.read"]}],
        "skills": _SKILLS,
        "supportsAuthenticatedExtendedCard": False,
    }
