"""Public agent endpoint proxy mounted on the primary API service.

This keeps `/api/v1/agent/*` available at `api.foundryops.io` even when edge
path routing to the dedicated `gremlin-agent-api` service is not configured.
"""

from __future__ import annotations

import os
from typing import Any

import httpx
from fastapi import APIRouter, Body, HTTPException
from fastapi.responses import JSONResponse, Response

router = APIRouter()

_DEFAULT_AGENT_API_BASE = "https://gremlin-agent-api-5pkec6diha-uc.a.run.app"


def _agent_api_base() -> str:
    return (
        os.getenv("AGENT_PUBLIC_API_BASE")
        or os.getenv("GREMLIN_AGENT_API_URL")
        or _DEFAULT_AGENT_API_BASE
    ).rstrip("/")


async def _forward_agent_request(
    method: str,
    path: str,
    payload: dict[str, Any] | None = None,
) -> Response:
    url = f"{_agent_api_base()}{path}"
    try:
        async with httpx.AsyncClient(timeout=20.0) as client:
            upstream = await client.request(method, url, json=payload)
    except httpx.RequestError as exc:
        raise HTTPException(status_code=502, detail=f"Agent API upstream unavailable: {exc}") from exc

    content_type = upstream.headers.get("content-type", "")
    if "application/json" in content_type.lower():
        try:
            data = upstream.json()
        except Exception:
            data = {"detail": upstream.text}
        return JSONResponse(status_code=upstream.status_code, content=data)

    media_type = content_type or None
    return Response(status_code=upstream.status_code, content=upstream.content, media_type=media_type)


@router.get("/api/v1/agent/tiers")
async def get_agent_tiers_proxy() -> Response:
    return await _forward_agent_request("GET", "/api/v1/agent/tiers")


@router.get("/api/v1/agent/licenses/keys")
async def get_agent_license_keys_proxy() -> Response:
    return await _forward_agent_request("GET", "/api/v1/agent/licenses/keys")


@router.post("/api/v1/agent/licenses/resolve")
async def resolve_install_token_proxy(
    body: dict[str, Any] = Body(...),
) -> Response:
    return await _forward_agent_request(
        "POST",
        "/api/v1/agent/licenses/resolve",
        payload=body,
    )

