import logging
import os

import requests

from planemapper.constants import AIRSPACE_PATH
from planemapper.provisioning import ProvisioningError

log = logging.getLogger(__name__)

_EMPTY_GEOJSON = '{"type": "FeatureCollection", "features": []}'
_OPENAIP_URL = "https://api.openaip.net/api/airspaces"


def download(lat: float, lon: float, radius_nm: float) -> None:
    api_key = os.environ.get("OPENAIP_API_KEY")
    AIRSPACE_PATH.parent.mkdir(parents=True, exist_ok=True)

    if not api_key:
        log.warning(
            "OPENAIP_API_KEY not set — writing empty airspace cache; "
            "airspace outlines will not be shown"
        )
        AIRSPACE_PATH.write_text(_EMPTY_GEOJSON)
        return

    radius_deg = radius_nm / 60.0
    bbox = [lon - radius_deg, lat - radius_deg, lon + radius_deg, lat + radius_deg]
    resp = requests.get(
        _OPENAIP_URL,
        params={"bbox": ",".join(f"{v:.6f}" for v in bbox)},
        headers={"x-openaip-api-key": api_key},
        timeout=30,
    )
    if not resp.ok:
        raise ProvisioningError(f"OpenAIP API failed: {resp.status_code}")
    AIRSPACE_PATH.write_text(resp.text)
    log.info("airspace data saved to %s", AIRSPACE_PATH)
