from __future__ import annotations

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

from app_dependencies import get_runtime
from route_helpers import read_json_request
from web_runtime import WebAppRuntime

router = APIRouter()


@router.post("/rtc/offer")
async def rtc_offer(
    request: Request,
    runtime: WebAppRuntime = Depends(get_runtime),
) -> JSONResponse:
    try:
        payload = await read_json_request(request)
    except ValueError as exc:
        return JSONResponse({"error": str(exc)}, status_code=400)

    answer = await runtime.rtc_manager.handle_offer(payload)
    if answer is None:
        return JSONResponse(
            {"error": "WebRTC backend unavailable on host (aiortc is not installed)."},
            status_code=503,
        )
    return JSONResponse(answer)
