"""
Demo Session Routes - Proxy to demo-session service
"""

from fastapi import APIRouter, Request, HTTPException
from fastapi.responses import JSONResponse
import httpx
import structlog

from app.core.config import settings
from app.core.header_manager import header_manager

logger = structlog.get_logger()

router = APIRouter()


@router.api_route("/demo/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH"])
async def proxy_demo_service(path: str, request: Request):
    """
    Proxy all demo requests to the demo-session service
    These endpoints are public and don't require authentication
    """
    # Build the target URL
    demo_service_url = settings.DEMO_SESSION_SERVICE_URL.rstrip('/')
    target_url = f"{demo_service_url}/api/v1/demo/{path}"

    # Get request body
    body = None
    if request.method in ["POST", "PUT", "PATCH"]:
        body = await request.body()

    # Use unified HeaderManager for consistent header forwarding
    headers = header_manager.get_all_headers_for_proxy(request)

    try:
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.request(
                method=request.method,
                url=target_url,
                headers=headers,
                params=request.query_params,
                content=body
            )

            # Return the response
            return JSONResponse(
                content=response.json() if response.content else {},
                status_code=response.status_code,
                headers=dict(response.headers)
            )

    except httpx.RequestError as e:
        logger.error("Failed to proxy to demo-session service", error=str(e), url=target_url)
        raise HTTPException(status_code=503, detail="Demo service unavailable")
    except Exception as e:
        logger.error("Unexpected error proxying to demo-session service", error=str(e))
        raise HTTPException(status_code=500, detail="Internal server error")
