from typing import Any

from fastapi import APIRouter, HTTPException, status

from app.services.geocoding import (
    TiandituGeocodeRequest,
    TiandituGeocodingAPIError,
    TiandituGeocodingConfigError,
    geocode_tianditu,
)

router = APIRouter()


@router.post(
    "/tianditu/geocode",
    summary="Tianditu Geocoding",
    description="调用天地图地理编码服务，将结构化地址转换为经纬度",
)
async def tianditu_geocode(request: TiandituGeocodeRequest) -> dict[str, Any]:
    try:
        return await geocode_tianditu(request)
    except TiandituGeocodingConfigError as exc:
        raise HTTPException(
            status_code=status.HTTP_503_SERVICE_UNAVAILABLE,
            detail=str(exc),
        ) from exc
    except TiandituGeocodingAPIError as exc:
        raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc
