"""Fetch the latest China airport METAR reports with a Skyviewor trial key.

Python 3.11+; install with: python -m pip install httpx
Set SKYVIEWOR_API_KEY in your shell. Never put the key in this file.
"""

import argparse
import json
import os
import re

import httpx

API_URL = "https://data.skyviewor.io/v1/metar"


def airport_list(value: str) -> str:
    airports = [item.strip().upper() for item in value.split(",")]
    if not airports or any(not re.fullmatch(r"[A-Z]{4}", item) for item in airports):
        raise argparse.ArgumentTypeError("Use comma-separated four-letter ICAO codes, such as ZBAA,ZSPD")
    return ",".join(airports)


def fetch(airports: str, key: str) -> dict:
    with httpx.Client(timeout=15.0) as client:
        response = client.get(
            API_URL,
            params={"airports": airports, "mode": "raw"},
            headers={"Authorization": f"Bearer {key}"},
        )
        response.raise_for_status()
        return response.json()


def main() -> None:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--airports", type=airport_list, default="ZBAA,ZSPD")
    args = parser.parse_args()
    key = os.getenv("SKYVIEWOR_API_KEY")
    if not key:
        parser.error("Set SKYVIEWOR_API_KEY in your environment before making a live request")
    try:
        print(json.dumps(fetch(args.airports, key), indent=2, ensure_ascii=False))
    except httpx.HTTPStatusError as exc:
        raise SystemExit(f"Skyviewor returned HTTP {exc.response.status_code}; check the key, airport codes, and access status") from None
    except httpx.HTTPError as exc:
        raise SystemExit(f"Request failed: {type(exc).__name__}") from None


if __name__ == "__main__":
    main()
