#!/usr/bin/env python3
"""Generate growing-zone metadata for existing Agrarian terrain tiles.

Only source-backed/generated tiles with explicit profiles are emitted. That
keeps the Earth-scale path repeatable without fetching or calculating metadata
for placeholder squares that do not exist in-game yet.
"""

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_growing_zone_metadata.json"
GROWING_READY_STATUSES = {"source_data_found", "generated", "validated", "packaged", "published"}
GROWING_ZONE_OVERRIDES = {
    "gz_us_ca_pacifica_utm10n_e544_n4160": {
        "growing_zone_label": "USDA 10a",
        "climate_profile": "coastal_mediterranean_mild",
        "growing_season_start_day": 46,
        "growing_season_end_day": 350,
        "frost_free_days": 305,
        "min_average_growing_temp_c": 7.0,
        "crop_safety_buffer_days": 14,
        "data_basis": "MVP conservative coastal Pacifica profile; replace with authoritative zone/temperature datasets during regional expansion.",
    }
}


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

    for tile in registry.get("tiles", []):
        tile_id = tile.get("tile_id")
        status = tile.get("status")
        if status not in GROWING_READY_STATUSES or tile_id not in GROWING_ZONE_OVERRIDES:
            continue

        grid = tile.get("grid", {})
        records.append(
            {
                "tile_id": tile_id,
                "center_latitude": grid.get("center_latitude"),
                "center_longitude": grid.get("center_longitude"),
                **GROWING_ZONE_OVERRIDES[tile_id],
            }
        )

    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": "Only tiles with real source status and explicit growing-zone data are emitted.",
                "tiles": records,
            },
            indent=2,
        )
        + "\n",
        encoding="utf-8",
    )

    print(f"Wrote {len(records)} tile growing-zone metadata record(s) to {OUTPUT_PATH.relative_to(ROOT)}")


if __name__ == "__main__":
    main()
