"""
POI Context Proxy Router
Forwards all POI context requests to the External 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("/{path:path}", methods=["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"])
async def proxy_poi_context(request: Request, path: str):
    """
    Proxies all POI context requests to the External Service.

    Forwards requests from /api/v1/poi-context/* to external-service:8000/api/v1/poi-context/*

    Args:
        request: The incoming request
        path: The path after /api/v1/poi-context/

    Returns:
        JSONResponse with the response from the external service

    Raises:
        HTTPException: If the external service is unavailable or returns an error
    """
    try:
        # Construct the external service URL
        external_url = f"{settings.EXTERNAL_SERVICE_URL}/poi-context/{path}"

        logger.debug("Proxying POI context request",
                    method=request.method,
                    path=path,
                    external_url=external_url)

        # Get request body for POST/PUT/PATCH requests
        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)

        # Make the request to the external service
        async with httpx.AsyncClient(timeout=60.0) as client:
            response = await client.request(
                method=request.method,
                url=external_url,
                params=request.query_params,
                headers=headers,
                content=body
            )

            logger.debug("POI context proxy response",
                        status_code=response.status_code,
                        path=path)

            # Return the response from the external service
            return JSONResponse(
                content=response.json() if response.text else None,
                status_code=response.status_code,
                headers=dict(response.headers)
            )

    except httpx.RequestError as exc:
        logger.error("External service POI request failed",
                    error=str(exc),
                    path=path,
                    external_url=external_url)
        raise HTTPException(
            status_code=503,
            detail=f"POI service unavailable: {exc}"
        )
    except Exception as exc:
        logger.error("Unexpected error in POI proxy",
                    error=str(exc),
                    path=path)
        raise HTTPException(
            status_code=500,
            detail="Internal server error in POI proxy"
        )
