"""
MCP OAuth 2.0 discovery endpoint.

PropelAuth handles the full MCP OAuth 2.1 flow (DCR, authorize, token).
We only serve the Protected Resource Metadata (RFC 9728) so MCP clients
know where to find PropelAuth as the authorization server.

Endpoint (mounted on the main FastAPI app):
    GET  /.well-known/oauth-protected-resource   RFC 9728
"""

from __future__ import annotations

import os

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

discovery_router = APIRouter(tags=["MCP OAuth Discovery"])


def _backend_url(request: Request) -> str:
    """Derive the public backend URL from the incoming request."""
    override = os.getenv("BACKEND_URL")
    if override:
        return override.rstrip("/")
    scheme = request.headers.get("x-forwarded-proto", request.url.scheme)
    return f"{scheme}://{request.url.netloc}"


@discovery_router.get("/.well-known/oauth-protected-resource")
async def protected_resource_metadata(request: Request):
    """RFC 9728 — Protected Resource Metadata.

    Tells MCP clients that PropelAuth is the authorization server.
    The client will then fetch PropelAuth's authorization server metadata
    at {PROPELAUTH_AUTH_URL}/.well-known/oauth-authorization-server/oauth/2.1
    to discover the authorize, token, and register endpoints.
    """
    base = _backend_url(request)
    pa_auth_url = os.getenv("PROPELAUTH_AUTH_URL", "")
    return JSONResponse(
        content={
            "resource": f"{base}/mcp/",
            "authorization_servers": [f"{pa_auth_url}/oauth/2.1"],
            "bearer_methods_supported": ["header"],
        },
        headers={"Access-Control-Allow-Origin": "*"},
    )
