"""OAuth metadata for the actual agent authorization server, gated for rollout."""

from fastapi import APIRouter, Depends
from fastapi.responses import JSONResponse

from src.config import get_settings
from src.core.agent_card import AGENT_CARD_PATH, build_agent_card
from src.domain.agent_access.dependencies import require_agent_access
from src.domain.agent_access.schemas import SCOPE_PERMISSIONS

router = APIRouter(dependencies=[Depends(require_agent_access)])


@router.api_route(
    "/api/discovery/agent-card.json", methods=["GET", "HEAD"], include_in_schema=False
)
@router.api_route(AGENT_CARD_PATH, methods=["GET", "HEAD"], include_in_schema=False)
async def agent_card():
    settings = get_settings()
    return JSONResponse(
        build_agent_card(settings.app_url.rstrip("/"), a2a_url=settings.agent_a2a_url),
        headers={"Cache-Control": "public, max-age=300"},
    )


@router.api_route(
    "/api/discovery/oauth-authorization-server", methods=["GET", "HEAD"], include_in_schema=False
)
@router.api_route(
    "/.well-known/oauth-authorization-server", methods=["GET", "HEAD"], include_in_schema=False
)
async def authorization_server_metadata():
    settings = get_settings()
    origin = settings.app_url.rstrip("/")
    base = f"{origin}/api/agent-access"
    return JSONResponse(
        {
            "issuer": origin,
            "authorization_endpoint": f"{origin}/agents/authorize",
            "token_endpoint": f"{base}/token",
            "registration_endpoint": f"{base}/clients",
            "revocation_endpoint": f"{base}/revoke",
            "response_types_supported": ["code"],
            "grant_types_supported": ["authorization_code", "refresh_token", "client_credentials"],
            "code_challenge_methods_supported": ["S256"],
            # Only "none" is real for self-service DCR clients (public, PKCE-only —
            # see ClientCreate). Service accounts do send a secret at /token, but
            # those are dashboard-created, not self-registered here, so a DCR
            # client has no way to act on "client_secret_post" being listed; it
            # only causes a real client (e.g. Claude) to request it and 422.
            "token_endpoint_auth_methods_supported": ["none"],
            "revocation_endpoint_auth_methods_supported": ["none"],
            "scopes_supported": list(SCOPE_PERMISSIONS),
            "service_documentation": f"{origin}/auth.md",
        },
        headers={"Cache-Control": "no-store"},
    )
