import os
import httpx
from fastapi import APIRouter, Depends, HTTPException, Query, Security
from fastapi.security import APIKeyHeader

API_KEY = os.environ.get("API_KEY", "")

router = APIRouter()

_api_key_header = APIKeyHeader(name="X-API-Key", auto_error=False)


def _require_api_key(key: str = Security(_api_key_header)):
    if not API_KEY:
        raise HTTPException(status_code=500, detail="API_KEY not configured on server")
    if key != API_KEY:
        raise HTTPException(status_code=403, detail="Invalid API key")


def _require_google_key():
    GOOGLE_MAPS_API_KEY = os.environ.get("GOOGLE_MAPS_API_KEY", "")
    if not GOOGLE_MAPS_API_KEY:
        raise HTTPException(status_code=500, detail="GOOGLE_MAPS_API_KEY not configured")
    return GOOGLE_MAPS_API_KEY


@router.get("/geocode", dependencies=[Depends(_require_api_key)])
async def geocode(lat: float, lng: float):
    """Proxy Google Geocoding API — returns the raw results array."""
    key = _require_google_key()
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            "https://maps.googleapis.com/maps/api/geocode/json",
            params={"latlng": f"{lat},{lng}", "key": key},
        )
        resp.raise_for_status()
        return resp.json()


@router.post("/autocomplete", dependencies=[Depends(_require_api_key)])
async def autocomplete(body: dict):
    """Proxy Google Places Autocomplete API."""
    key = _require_google_key()
    async with httpx.AsyncClient() as client:
        resp = await client.post(
            "https://places.googleapis.com/v1/places:autocomplete",
            headers={"X-Goog-Api-Key": key},
            json=body,
        )
        resp.raise_for_status()
        return resp.json()


@router.get("/places/{place_id}", dependencies=[Depends(_require_api_key)])
async def get_place(place_id: str, fields: str = Query(..., description="Comma-separated Places API v1 field mask")):
    """Proxy Google Places API v1 — returns the raw place object."""
    key = _require_google_key()
    async with httpx.AsyncClient() as client:
        resp = await client.get(
            f"https://places.googleapis.com/v1/places/{place_id}",
            headers={
                "X-Goog-Api-Key": key,
                "X-Goog-FieldMask": fields,
            },
        )
        resp.raise_for_status()
        return resp.json()
