#!/usr/bin/env python3
"""Generate weather lookup coordinates for source-backed Agrarian tiles.

The weather provider can request live conditions for any active tile with
latitude/longitude. This manifest is intentionally generated from the registry
instead of per-tile hard-coded overrides, so future source-backed tiles are
eligible automatically when they are added to the registry.
"""

from __future__ import annotations

import json
from datetime import datetime, timezone
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
REGISTRY_PATH = ROOT / "Data" / "Tiles" / "ground_zero_tiles.json"
OUTPUT_PATH = ROOT / "Data" / "Tiles" / "tile_weather_manifest.json"
WEATHER_READY_STATUSES = {"source_data_found", "generated", "validated", "packaged", "published"}


def main() -> None:
    registry = json.loads(REGISTRY_PATH.read_text(encoding="utf-8"))
    records = []

    for tile in registry.get("tiles", []):
        status = tile.get("status")
        tile_id = tile.get("tile_id")
        grid = tile.get("grid", {})
        weather_lookup = tile.get("weather_lookup_metadata", {})
        latitude = weather_lookup.get("lookup_latitude", grid.get("center_latitude"))
        longitude = weather_lookup.get("lookup_longitude", grid.get("center_longitude"))
        if status not in WEATHER_READY_STATUSES or not tile_id or latitude is None or longitude is None:
            continue

        records.append(
            {
                "tile_id": tile_id,
                "center_latitude": latitude,
                "center_longitude": longitude,
                "coordinate_source": weather_lookup.get("coordinate_source", "tile_center"),
                "provider": weather_lookup.get("primary_provider", "open-meteo"),
                "fallback_provider": weather_lookup.get("fallback_provider", ""),
                "fallback_provider_eligible": bool(weather_lookup.get("fallback_provider_eligible", False)),
                "lookup_rule": weather_lookup.get(
                    "lookup_rule",
                    "Use tile center latitude/longitude for live MVP weather and temperature snapshots.",
                ),
            }
        )

    OUTPUT_PATH.write_text(
        json.dumps(
            {
                "schema_version": 1,
                "generated_at_utc": datetime.now(timezone.utc).replace(microsecond=0).isoformat().replace("+00:00", "Z"),
                "source_registry": str(REGISTRY_PATH.relative_to(ROOT)),
                "generation_rule": "Every source-backed/generated tile with center coordinates is emitted; unknown placeholders are skipped.",
                "tiles": records,
            },
            indent=2,
        )
        + "\n",
        encoding="utf-8",
    )

    print(f"Wrote {len(records)} tile weather manifest record(s) to {OUTPUT_PATH.relative_to(ROOT)}")


if __name__ == "__main__":
    main()
