#!/usr/bin/env python3
"""Verify Ground Zero weather lookup coordinates are registry-driven."""

from __future__ import annotations

import json
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
REGISTRY = ROOT / "Data" / "Tiles" / "ground_zero_tiles.json"
SCHEMA = ROOT / "Data" / "Tiles" / "tile_registry.schema.json"
MANIFEST = ROOT / "Data" / "Tiles" / "tile_weather_manifest.json"
GENERATOR = ROOT / "Scripts" / "generate_tile_weather_manifest.py"
GAME_STATE_H = ROOT / "Source" / "AgrarianGame" / "AgrarianGameState.h"
TDD = ROOT / "Docs" / "TechnicalDesignDocument.md"
REGISTRY_DOC = ROOT / "Docs" / "Terrain" / "TileRegistrySchema.md"
ROADMAP = ROOT / "AGRARIAN_DEVELOPMENT_ROADMAP.md"

GROUND_ZERO_TILE_ID = "gz_us_ca_pacifica_utm10n_e544_n4160"
GROUND_ZERO_LATITUDE = 37.5925
GROUND_ZERO_LONGITUDE = -122.4995


def assert_close(name: str, actual: float, expected: float) -> None:
    if abs(actual - expected) > 0.00001:
        raise RuntimeError(f"{name} expected {expected}, got {actual}")


def main() -> None:
    registry = json.loads(REGISTRY.read_text(encoding="utf-8"))
    schema_text = SCHEMA.read_text(encoding="utf-8")
    manifest = json.loads(MANIFEST.read_text(encoding="utf-8"))
    generator_text = GENERATOR.read_text(encoding="utf-8")
    game_state_text = GAME_STATE_H.read_text(encoding="utf-8")

    ground_zero = next((tile for tile in registry["tiles"] if tile.get("tile_id") == GROUND_ZERO_TILE_ID), None)
    if ground_zero is None:
        raise RuntimeError("Ground Zero tile is missing from registry")

    grid = ground_zero["grid"]
    lookup = ground_zero.get("weather_lookup_metadata")
    if not lookup:
        raise RuntimeError("Ground Zero tile is missing weather_lookup_metadata")

    assert_close("grid center latitude", float(grid["center_latitude"]), GROUND_ZERO_LATITUDE)
    assert_close("grid center longitude", float(grid["center_longitude"]), GROUND_ZERO_LONGITUDE)
    assert_close("weather lookup latitude", float(lookup["lookup_latitude"]), GROUND_ZERO_LATITUDE)
    assert_close("weather lookup longitude", float(lookup["lookup_longitude"]), GROUND_ZERO_LONGITUDE)

    if lookup.get("coordinate_source") != "tile_center":
        raise RuntimeError("Ground Zero weather coordinate_source should be tile_center")
    if lookup.get("primary_provider") != "open-meteo":
        raise RuntimeError("Ground Zero primary weather provider should be open-meteo")
    if lookup.get("fallback_provider") != "noaa-nws":
        raise RuntimeError("Ground Zero fallback weather provider should be noaa-nws")
    if lookup.get("fallback_provider_eligible") is not True:
        raise RuntimeError("Ground Zero should be NOAA/NWS fallback eligible")

    weather_records = [tile for tile in manifest.get("tiles", []) if tile.get("tile_id") == GROUND_ZERO_TILE_ID]
    if len(weather_records) != 1:
        raise RuntimeError(f"Expected exactly one Ground Zero weather manifest record, got {len(weather_records)}")
    manifest_record = weather_records[0]
    assert_close("manifest latitude", float(manifest_record["center_latitude"]), GROUND_ZERO_LATITUDE)
    assert_close("manifest longitude", float(manifest_record["center_longitude"]), GROUND_ZERO_LONGITUDE)
    if manifest_record.get("coordinate_source") != "tile_center":
        raise RuntimeError("Weather manifest should preserve the coordinate source")
    if manifest_record.get("provider") != "open-meteo":
        raise RuntimeError("Weather manifest should preserve the primary provider")
    if manifest_record.get("fallback_provider") != "noaa-nws":
        raise RuntimeError("Weather manifest should preserve the fallback provider")

    required_snippets = {
        "schema": ["weather_lookup_metadata", "lookup_latitude", "fallback_provider_eligible"],
        "generator": ["weather_lookup_metadata", "coordinate_source", "fallback_provider_eligible"],
        "game_state": ["ActiveTileLatitude = 37.5925f", "ActiveTileLongitude = -122.4995f"],
        "tdd": ["Ground Zero weather lookup coordinates", "37.5925", "-122.4995"],
        "registry_doc": ["terrain_tile_weather_lookup_metadata", "lookup_latitude", "primary_provider"],
        "roadmap": ["[x] Link Ground Zero tile coordinates to real-world weather lookup coordinates."],
    }
    checks = {
        "schema": schema_text,
        "generator": generator_text,
        "game_state": game_state_text,
        "tdd": TDD.read_text(encoding="utf-8"),
        "registry_doc": REGISTRY_DOC.read_text(encoding="utf-8"),
        "roadmap": ROADMAP.read_text(encoding="utf-8"),
    }
    missing = []
    for label, snippets in required_snippets.items():
        for snippet in snippets:
            if snippet not in checks[label]:
                missing.append(f"{label}: {snippet}")
    if missing:
        raise RuntimeError("Ground Zero weather lookup verification failed: " + "; ".join(missing))

    print("Ground Zero weather lookup coordinate verification complete.")


if __name__ == "__main__":
    main()
