"""Reprodukuje číselné podklady tří grafů oteplení. Vyžaduje numpy a h5py.

Spuštění: python prubehy.py ADRESAR_PRO_PUVODNI_DATA
Vstupní soubory se stáhnou jednou. Výstupy vzniknou vedle tohoto skriptu.
Grafy pak vykreslí kreslit-prubehy.py ze zveřejněných CSV a JSON.
"""

import argparse
import csv
import json
from concurrent.futures import ThreadPoolExecutor
from math import isfinite
from pathlib import Path
from statistics import mean
from urllib.request import Request, urlopen

import h5py
import numpy as np


OUT = Path(__file__).resolve().parent
CEDA = "https://dap.ceda.ac.uk/badc/ar6_wg1/data/spm/spm_08/v20210809/panel_a"
ATLAS_REV = "ed29da33d38ae767d19caafd4cde06042cbe00f4"
ATLAS_PATH = "datasets-aggregated-regionally/data/CMIP6/CMIP6_tas_landsea"
ATLAS_RAW = f"https://raw.githubusercontent.com/IPCC-WG1/Atlas/{ATLAS_REV}/{ATLAS_PATH}"
FAIR_RAW = "https://raw.githubusercontent.com/chrisroadmap/cmip7-scenariomip/1.1.1/data/fair-outputs/fair_run.nc"
SSPS = ("SSP1-1.9", "SSP1-2.6", "SSP2-4.5", "SSP3-7.0", "SSP5-8.5")


def fetch(url, path):
    if not path.exists():
        path.parent.mkdir(parents=True, exist_ok=True)
        request = Request(url, headers={"User-Agent": "Klimatologie.eu data reproduction"})
        with urlopen(request, timeout=90) as response:
            data = response.read()
        path.write_bytes(data)
    return path


def ipcc_means(cache):
    # Fyfe a kol., CEDA, obr. SPM.8a (10.5285/98af2184e13e4b91893ab72f301790db).
    with (OUT / "prubeh-ipcc.csv").open("w", encoding="utf-8", newline="") as output:
        writer = csv.writer(output, lineterminator="\n")
        writer.writerow(["scenario", "year", "p05_degC", "mean_degC", "p95_degC"])
        for scenario in SSPS:
            name = scenario.replace("-", "_").replace(".", "_") + ".csv"
            source = fetch(f"{CEDA}/tas_global_{name}", cache / name)
            with source.open(encoding="utf-8-sig") as file:
                for row in csv.DictReader(file):
                    writer.writerow([scenario, int(float(row["Year"])), row["5%"], row["Mean"], row["95%"]])


def world_months(path):
    with path.open(encoding="utf-8-sig") as file:
        reader = csv.DictReader(line for line in file if not line.startswith("#"))
        return {row["date"]: float(row["world"]) for row in reader}


def model_series(name, cache):
    model, _, variant = name.removeprefix("CMIP6_").removesuffix(".csv").split("_")
    historical = name.replace("_ssp245_", "_historical_")
    months = world_months(fetch(f"{ATLAS_RAW}/{historical}", cache / "atlas" / historical))
    months.update(world_months(fetch(f"{ATLAS_RAW}/{name}", cache / "atlas" / name)))
    annual = {}
    # Některé původní historické soubory vynechávají roky 1901–1949.
    # Uchováváme společné výchozí období a souvislý záznam od roku 1950.
    for year in [*range(1850, 1901), *range(1950, 2101)]:
        values = [months.get(f"{year}-{month:02d}", float("nan")) for month in range(1, 13)]
        if not all(map(isfinite, values)):
            return []  # Pro každý zobrazený model požadujeme celý shodný interval.
        annual[year] = mean(values)
    baseline = mean(annual[y] for y in range(1850, 1901))
    rows = []
    for year, value in annual.items():
        window = ""
        if 2015 <= year <= 2090:
            window = f"{mean(annual[y] for y in range(year - 9, year + 11)) - baseline:.6f}"
        rows.append([model, variant, year, f"{value - baseline:.6f}", window])
    return rows


def atlas_models(cache):
    # Data Atlasu IPCC a skupin CMIP6 (CC BY 4.0), Iturbide a kol. 2022.
    inventory_url = f"https://api.github.com/repos/IPCC-WG1/Atlas/contents/{ATLAS_PATH}?ref={ATLAS_REV}"
    inventory = json.loads(fetch(inventory_url, cache / "atlas-inventory.json").read_bytes())
    names = {entry["name"] for entry in inventory}
    pairs = sorted(name for name in names if "_ssp245_" in name and name.replace("_ssp245_", "_historical_") in names)
    with (OUT / "modely-ssp245.csv").open("w", encoding="utf-8", newline="") as output:
        writer = csv.writer(output, lineterminator="\n")
        writer.writerow(["model", "variant", "year", "annual_anomaly_degC", "twenty_year_anomaly_degC"])
        with ThreadPoolExecutor(max_workers=6) as pool:
            for rows in pool.map(model_series, pairs, [cache] * len(pairs)):
                writer.writerows(rows)


def fair_pathways(cache):
    # Sanderson a kol., vydání 1.1.1 (10.5281/zenodo.20713982), fair_run.nc.
    with h5py.File(fetch(FAIR_RAW, cache / "fair.nc"), "r") as data:
        bounds = data["timebounds"][:]
        surface = data["temperature"][:]  # časová hranice, scénář, nastavení
        # Shodná volba hranic let jako v autorském scripts/plotting.py.
        reference = surface[(bounds >= 1850) & (bounds <= 1901)].mean(axis=0)
        period = (bounds >= 2025) & (bounds <= 2100)
        q05, median, q95 = np.quantile(surface[period] - reference, [0.05, 0.50, 0.95], axis=2)
        result = {
            "source": "10.5281/zenodo.20713982", "release": "1.1.1",
            "model": "FaIR v2.2", "configurations": len(data["config"]),
            "reference": "1850–1900", "unit": "°C",
            "years": bounds[period].astype(int).tolist(),
            "scenarios": [
                {"id": scenario, "p05": q05[:, i].round(5).tolist(),
                 "median": median[:, i].round(5).tolist(), "p95": q95[:, i].round(5).tolist()}
                for i, scenario in enumerate(data["scenario"].asstr()[:])
            ],
        }
    with (OUT / "scenare-cmip7.json").open("w", encoding="utf-8", newline="\n") as file:
        json.dump(result, file, ensure_ascii=False, separators=(",", ":"))
        file.write("\n")


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("cache", type=Path)
    cache_dir = parser.parse_args().cache
    ipcc_means(cache_dir)
    atlas_models(cache_dir)
    fair_pathways(cache_dir)
