from __future__ import annotations

import json
import logging

from PIL import Image, ImageDraw

from planemapper.constants import AIRSPACE_PATH, COLOUR_AIRSPACE
from planemapper.renderer.projection import MapBounds, project

log = logging.getLogger(__name__)


def draw_airspace(image: Image.Image, bounds: MapBounds) -> None:
    try:
        data = json.loads(AIRSPACE_PATH.read_text(encoding="utf-8"))
    except FileNotFoundError:
        log.warning("airspace.geojson not found at %s — skipping airspace overlay", AIRSPACE_PATH)
        return
    draw = ImageDraw.Draw(image)
    for feature in data.get("features", []):
        geom = feature.get("geometry", {})
        if geom.get("type") != "Polygon":
            continue
        coords = geom.get("coordinates", [[]])[0]
        if len(coords) < 2:
            continue
        # GeoJSON is [lon, lat] — reverse at parse boundary
        points = [project(lat, lon, bounds) for lon, lat in coords]
        draw.line(points, fill=COLOUR_AIRSPACE, width=2)
