import os

import httpx
from starlette.requests import Request
from starlette.responses import JSONResponse


async def _proxy_wellknown(path: str) -> JSONResponse:
    issuer = os.environ.get("OAUTH_ISSUER", "https://api.obris.ai")
    url = f"{issuer}{path}"
    async with httpx.AsyncClient() as client:
        resp = await client.get(url, timeout=5.0)
    return JSONResponse(resp.json(), status_code=resp.status_code)


async def authorization_server_metadata(request: Request) -> JSONResponse:
    """
    RFC 8414 / RFC 9207 OAuth Authorization Server Metadata, proxied from the
    Django API. Exposed on the MCP server so clients like ChatGPT that look for
    /.well-known/oauth-authorization-server on the resource server can discover
    the registration_endpoint and other OAuth metadata.
    """
    return await _proxy_wellknown("/.well-known/oauth-authorization-server")


async def openid_configuration(request: Request) -> JSONResponse:
    """OpenID Connect Discovery, proxied from the Django API."""
    return await _proxy_wellknown("/.well-known/openid-configuration")


async def protected_resource_metadata(request: Request) -> JSONResponse:
    """
    RFC 9728 OAuth Protected Resource Metadata.
    GET /.well-known/oauth-protected-resource
    """
    mcp_server_url = os.environ.get("MCP_SERVER_URL", "https://mcp.obris.ai")
    issuer = os.environ.get("OAUTH_ISSUER", "https://api.obris.ai")
    scopes = os.environ.get("OAUTH_SCOPES", "openid topics:read topics:write").split()

    return JSONResponse({
        "resource": mcp_server_url.rstrip("/") + "/",
        "authorization_servers": [issuer],
        "scopes_supported": scopes,
        "bearer_methods_supported": ["header"],
    })