"""
Gas-fired plants: global coverage and evidence gaps
===================================================

Build typed Parquet, load all records, map reported locations, and inspect dated
capacity categories. The initial 3,998 WRI records in 113 countries are a
historical discovery baseline, not a current operating census. Source attribution:
World Resources Institute, Global Power Plant Database v1.3.0 repository snapshot,
CC BY 4.0. No CCGT/OCGT technology, current owner or current operation is inferred.
See the :doc:`interactive gas viewer </gas-database-viewer>`.
"""

import json
from pathlib import Path
from tempfile import TemporaryDirectory

import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.collections import PolyCollection

from energy_data_retrieval.gas_catalogue import build_parquet, capacity_summary, load_records

ROOT = next(p for p in (Path.cwd(), *Path.cwd().parents) if (p / "catalogues/gas").is_dir())
rows = load_records(ROOT / "catalogues/gas")
with TemporaryDirectory() as folder:
    snapshot = Path(folder) / "snapshot"
    manifest = build_parquet(ROOT / "catalogues/gas", snapshot)
    plants = pd.read_parquet(snapshot / "projects.parquet")
print("Plant records:", len(plants), "Countries:", plants.country_code.nunique())
print("Input fingerprint:", manifest["input_sha256"])
for field in ("installed_capacity_mw", "operational_capacity_mw", "planned_capacity_mw"):
    print(field, capacity_summary(rows, field))
print("Unknown current status:", int(plants.status.eq("unknown").sum()))
print("Unknown generation technology:", int(plants.technology.eq("unknown").sum()))
print(
    "Historical capacity with unknown measurement year:",
    plants.capacity_reference_year.isna().sum(),
)

# %%
# Reuse the repository's attributed Natural Earth boundaries; no network access.
world = json.loads(
    (ROOT / "examples/connectors/data/generation_coverage_world.geojson").read_text()
)
polygons = []
for feature in world["features"]:
    geometry = feature["geometry"]
    groups = geometry["coordinates"]
    if geometry["type"] == "Polygon":
        groups = [groups]
    polygons.extend(polygon[0] for polygon in groups)

fig, axes = plt.subplots(1, 2, figsize=(14, 5), layout="constrained")
axes[0].add_collection(
    PolyCollection(polygons, facecolor="#e6eaf0", edgecolor="white", linewidth=0.2)
)
located = plants.dropna(subset=["latitude", "longitude"])
axes[0].scatter(located.longitude, located.latitude, s=5, alpha=0.5, color="#b76319")
axes[0].set(
    xlim=(-180, 180),
    ylim=(-60, 85),
    xlabel="Longitude [degrees]",
    ylabel="Latitude [degrees]",
    title="Reported gas-plant locations",
)
axes[0].grid(alpha=0.15)
plants.country_code.value_counts().head(15).sort_values().plot.barh(ax=axes[1], color="#b76319")
axes[1].set(
    xlabel="Catalogue records",
    ylabel="Country code",
    title="Coverage leaders · not current market share",
)
fig.suptitle("Global gas-fired plants · historical WRI discovery baseline")
plt.show()

# %%
# Inspect one deterministic record and its provenance before using its ratings.
example = rows[0]
print("Example identity:", example["name"], example["external_ids_json"])
print("Capacity boundary:", example["capacity_scope"])
print("Historical MW evidence:", json.loads(example["evidence_json"])["historical_capacity_mw"])
print("Historical owner (not verified current owner):", example.get("historical_owner_names"))
