#!/usr/bin/env python3
"""Local static server with a tiny NOAA AWC proxy (METAR/TAF have no CORS)."""

from __future__ import annotations

import json
import os
import sys
import urllib.error
import urllib.request
from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
from urllib.parse import urlparse

ROOT = os.path.dirname(os.path.abspath(__file__))
PORT = int(os.environ.get("PORT", "8765"))
HOST = os.environ.get("HOST", "127.0.0.1")

UPSTREAM = {
    "/api/metar": "https://aviationweather.gov/api/data/metar?ids=FACT&format=json",
    "/api/taf": "https://aviationweather.gov/api/data/taf?ids=FACT&format=json",
}
OM_DEFAULT = (
    "https://api.open-meteo.com/v1/forecast"
    "?latitude=-33.9716&longitude=18.6021"
    "&current=temperature_2m,apparent_temperature,wind_speed_10m,"
    "wind_direction_10m,wind_gusts_10m,cloud_cover,visibility,weather_code,"
    "is_day,relative_humidity_2m"
    "&hourly=temperature_2m,wind_speed_10m,wind_direction_10m,wind_gusts_10m,"
    "cloud_cover,visibility,weather_code,is_day,precipitation_probability,"
    "cloud_cover_low,cloud_cover_mid,cloud_cover_high"
    "&wind_speed_unit=kn&visibility_unit=m"
    "&timezone=Africa%2FJohannesburg&forecast_days=2"
)

UA = "GoAroundTerrainDemo/1.0 (local preview; +https://127.0.0.1)"


class Handler(SimpleHTTPRequestHandler):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, directory=ROOT, **kwargs)

    def end_headers(self):
        if not self.path.startswith("/api/"):
            self.send_header("Cache-Control", "no-cache")
        super().end_headers()

    def do_GET(self):
        parsed = urlparse(self.path)
        path = parsed.path
        if path in UPSTREAM:
            return self.proxy(UPSTREAM[path])
        if path == "/api/forecast":
            return self.proxy(OM_DEFAULT)
        return super().do_GET()

    def proxy(self, url: str) -> None:
        try:
            req = urllib.request.Request(url, headers={"User-Agent": UA, "Accept": "application/json"})
            with urllib.request.urlopen(req, timeout=15) as resp:
                data = resp.read()
                ctype = resp.headers.get("Content-Type", "application/json; charset=utf-8")
                self.send_response(200)
                self.send_header("Content-Type", ctype)
                self.send_header("Cache-Control", "no-store")
                self.send_header("Access-Control-Allow-Origin", "*")
                self.send_header("Content-Length", str(len(data)))
                self.end_headers()
                self.wfile.write(data)
        except Exception as exc:  # noqa: BLE001 — local demo fallback
            payload = json.dumps({"error": str(exc), "upstream": url}).encode()
            code = 504 if isinstance(exc, (TimeoutError, urllib.error.URLError)) else 502
            self.send_response(code)
            self.send_header("Content-Type", "application/json")
            self.send_header("Cache-Control", "no-store")
            self.send_header("Content-Length", str(len(payload)))
            self.end_headers()
            self.wfile.write(payload)

    def log_message(self, fmt: str, *args) -> None:
        msg = args[0] if args else ""
        if isinstance(msg, str) and "/api/" in msg:
            super().log_message(fmt, *args)


def main() -> int:
    os.chdir(ROOT)
    httpd = ThreadingHTTPServer((HOST, PORT), Handler)
    print(f"Go Around terrain demo http://{HOST}:{PORT}/  (ctrl+c to stop)", flush=True)
    try:
        httpd.serve_forever()
    except KeyboardInterrupt:
        print("\nstopped", flush=True)
    return 0


if __name__ == "__main__":
    sys.exit(main())
