# gateway/app/routes/geocoding.py

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_geocoding(request: Request, path: str):
    """
    Proxies all geocoding requests to the External Service geocoding endpoints.

    Forwards requests from /api/v1/geocoding/* to external-service:8000/api/v1/geocoding/*
    """
    try:
        # Construct the external service URL
        external_url = f"{settings.EXTERNAL_SERVICE_URL}/api/v1/geocoding/{path}"

        # Get request body for POST/PUT/PATCH
        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 proxied request
        async with httpx.AsyncClient(timeout=30.0) as client:
            response = await client.request(
                method=request.method,
                url=external_url,
                params=request.query_params,
                headers=headers,
                content=body
            )

            # Return the response from 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 geocoding request failed", error=str(exc), path=path)
        raise HTTPException(
            status_code=503,
            detail=f"Geocoding service unavailable: {exc}"
        )
    except httpx.HTTPStatusError as exc:
        logger.error(
            f"External service geocoding responded with error {exc.response.status_code}",
            detail=exc.response.text,
            path=path
        )
        raise HTTPException(
            status_code=exc.response.status_code,
            detail=f"Geocoding service error: {exc.response.text}"
        )
    except Exception as exc:
        logger.error("Unexpected error in geocoding proxy", error=str(exc), path=path)
        raise HTTPException(
            status_code=500,
            detail="Internal server error in geocoding proxy"
        )
