"""Comparative calculations for the closing chapter of the combined edition.

Reads only files already committed by the two studies and writes CSV tables to
edition/analysis/results/. Standard library only. Run from the repository root:

    python3 edition/analysis/compare.py

Nothing here changes either study's own results. Every figure produced is new
to the combined edition and is labelled as such on the website.
"""
import csv
import json
import math
import statistics
from pathlib import Path

ROOT = Path(__file__).resolve().parents[2]
OUT = Path(__file__).resolve().parent / "results"

POP = ROOT / "results" / "panel_scored_observations.csv"
POP_PANEL = ROOT / "data" / "forecast_panel_unified.csv"
BIRTHS = ROOT / "website" / "data" / "births.json"
AIR = ROOT / "transport" / "results" / "airport_scores.csv"
RAIL = ROOT / "transport" / "results" / "rail_comparisons.csv"

# Wang Peian's medium scenario as reproduced in ECNU Table 1, millions of births,
# 2016-2025. Copied from scripts/check_audit.py, which verifies it against the panel.
COMMISSION_PATH = dict(zip(range(2016, 2026), [17.672, 21.099, 21.886, 20.773, 19.358,
                                               16.891, 16.160, 15.499, 14.885, 14.329]))
POP_2025 = 1404.89  # NBS 2025 communique, year-end, millions (as used in the panel)


def rows(path):
    with open(path, newline="", encoding="utf-8") as f:
        return list(csv.DictReader(f))


def write(name, fields, data):
    OUT.mkdir(parents=True, exist_ok=True)
    with open(OUT / name, "w", newline="", encoding="utf-8") as f:
        w = csv.DictWriter(f, fieldnames=fields, lineterminator="\n")
        w.writeheader()
        for r in data:
            w.writerow({k: (round(v, 4) if isinstance(v, float) else v) for k, v in r.items()})


def summarize(label, study, kind, pairs, units, horizons=None):
    """pairs: list of (unit_id, forecast, actual). Ratio is forecast / actual."""
    ratios = [f / a for _, f, a in pairs]
    logs = [abs(math.log(r)) for r in ratios]
    return {
        "group": label, "study": study, "record_kind": kind,
        "rows": len(pairs), "units": len(set(units)),
        "forecast_above_actual": sum(r > 1 for r in ratios),
        "median_ratio": statistics.median(ratios),
        "median_abs_log_factor": math.exp(statistics.median(logs)),
        "min_ratio": min(ratios), "max_ratio": max(ratios),
        "median_horizon_years": statistics.median(horizons) if horizons else "",
    }


def common_scale():
    pop = rows(POP)
    primary = [r for r in pop if r["is_dedup_primary"] == r["is_primary_variant"] == "1"]
    emp = [r for r in primary if r["record_type"] == "forecast"
           and r["plan_indicator_nature"] == "empirical_projection"]
    sims = [r for r in primary if r["record_type"] == "forecast"
            and r["plan_indicator_nature"] == "counterfactual_policy_sim"]
    targets = [r for r in primary if r["record_type"] in ("plan_target", "policy_ceiling")]

    def pairs(sel):
        return [(r["obs_id"], float(r["forecast_value"]), float(r["actual_value"])) for r in sel]

    groups = []
    fixed = [r for r in emp if r["outcome_metric"] == "total_population_m" and int(r["horizon_years"]) > 0]
    assert len(fixed) == 36, len(fixed)  # same sample as the population study's headline mean
    groups.append(summarize("Population totals, fixed year", "population", "prediction",
                            pairs(fixed), [r["study_id"] for r in fixed],
                            [int(r["horizon_years"]) for r in fixed if r["horizon_years"]]))
    peaks = [r for r in emp if r["outcome_metric"] == "peak_population_m"]
    groups.append(summarize("Population peak size", "population", "prediction",
                            pairs(peaks), [r["study_id"] for r in peaks],
                            [int(r["horizon_years"]) for r in peaks if r["horizon_years"]]))
    births = [r for r in emp if r["outcome_metric"] == "annual_births_m"]
    groups.append(summarize("Annual births", "population", "prediction",
                            pairs(births), [r["study_id"] for r in births],
                            [int(r["horizon_years"]) for r in births if r["horizon_years"]]))
    sim_births = [r for r in sims if r["outcome_metric"] == "annual_births_m"]
    groups.append(summarize("Peak births after a policy change", "population", "conditional scenario",
                            pairs(sim_births), [r["study_id"] for r in sim_births],
                            [int(r["horizon_years"]) for r in sim_births if r["horizon_years"]]))
    plan = [r for r in targets if r["outcome_metric"] == "total_population_m"]
    assert len(plan) == 11, len(plan)
    groups.append(summarize("Population plan targets and ceilings", "population", "target",
                            pairs(plan), [r["study_id"] for r in plan],
                            [int(r["horizon_years"]) for r in plan if r["horizon_years"]]))

    air = rows(AIR)
    assert len(air) == 11
    groups.append(summarize("Airport passengers, target year", "transport", "prediction",
                            [(r["airport"], float(r["forecast"]), float(r["actual"])) for r in air],
                            [r["airport"] for r in air],
                            [int(r["target_year"]) - int(r["vintage"][:4]) for r in air]))
    rail = [r for r in rows(RAIL) if r["comparison"] in ("appraisal table", "phased rollout")]
    groups.append(summarize("Metro line ridership", "transport", "prediction",
                            [(r["case"], float(r["forecast"]), float(r["comparable_value"])) for r in rail],
                            [r["case"] for r in rail]))
    fields = list(groups[0])
    write("common_scale.csv", fields, groups)
    return groups


def stock_flow():
    pop = {r["obs_id"]: r for r in rows(POP)}
    out = []
    for producer, flow_id, stock_id in [
        ("Population commission expert group (2015)", "F12_births_2020", "F12_pop_2020"),
        ("Chen Wei, Renmin University (2006)", "F08_births_2006_2015", "F08_C17_pop_2015"),
    ]:
        f, s = pop[flow_id], pop[stock_id]
        out.append({"producer": producer,
                    "flow_row": flow_id, "flow_target": f["target_year"], "flow_pct_error": float(f["pct_error"]),
                    "stock_row": stock_id, "stock_target": s["target_year"], "stock_pct_error": float(s["pct_error"])})
    write("stock_flow_pairs.csv", list(out[0]), out)

    births = {d["year"]: d["births_m"] for d in json.loads(BIRTHS.read_text())}
    observed = sum(births[y] for y in range(2016, 2026))
    projected = sum(COMMISSION_PATH.values())
    arith = [
        {"quantity": "Observed births 2016-2025 (millions)", "value": observed},
        {"quantity": "Commission medium path births 2016-2025 (millions)", "value": projected},
        {"quantity": "Projected minus observed (millions)", "value": projected - observed},
        {"quantity": "Projected / observed births, ten-year total", "value": projected / observed},
        {"quantity": "2025 year-end population (millions)", "value": POP_2025},
        {"quantity": "Observed 2016-2025 births as % of 2025 population", "value": 100 * observed / POP_2025},
        {"quantity": "Excess projected births as % of 2025 population", "value": 100 * (projected - observed) / POP_2025},
    ]
    write("stock_flow_arithmetic.csv", ["quantity", "value"], arith)
    return out, arith


def aggregation():
    air = rows(AIR)
    F = sum(float(r["forecast"]) for r in air)
    A = sum(float(r["actual"]) for r in air)
    out = [{"excluded": "None", "n": len(air), "below_forecast": sum(float(r["actual"]) < float(r["forecast"]) for r in air),
            "median_attainment_pct": statistics.median(100 * float(r["actual"]) / float(r["forecast"]) for r in air),
            "pooled_attainment_pct": 100 * A / F,
            "share_of_combined_forecast_pct": "", "share_of_combined_actual_pct": ""}]
    for r in sorted(air, key=lambda r: -float(r["forecast"])):
        rest = [x for x in air if x is not r]
        f, a = float(r["forecast"]), float(r["actual"])
        out.append({"excluded": r["airport"], "n": len(rest),
                    "below_forecast": sum(float(x["actual"]) < float(x["forecast"]) for x in rest),
                    "median_attainment_pct": statistics.median(100 * float(x["actual"]) / float(x["forecast"]) for x in rest),
                    "pooled_attainment_pct": 100 * (A - a) / (F - f),
                    "share_of_combined_forecast_pct": 100 * f / F, "share_of_combined_actual_pct": 100 * a / A})
    write("airport_leave_one_out.csv", list(out[0]), out)
    return out


def roles():
    """Producer, commissioner and adopter of each population study in the scored panel."""
    scored = {r["study_id"] for r in rows(POP)}
    panel = [r for r in rows(POP_PANEL) if r["study_id"] in scored]
    by = {}
    for r in panel:
        s = by.setdefault(r["study_id"], {"study_id": r["study_id"], "citation": r["citation_short"],
                                          "producer": r["author_institution"], "commissioner": r["commissioner"],
                                          "adopter": r["adopter"], "sponsor_spec_a": r["sponsor_spec_a"],
                                          "record_types": set()})
        s["record_types"].add(r["record_type"] if r["plan_indicator_nature"] != "counterfactual_policy_sim"
                              else "conditional_scenario")
    out = []
    for s in sorted(by.values(), key=lambda s: s["study_id"]):
        s["record_types"] = "|".join(sorted(s["record_types"]))
        s["adopted_by_state_body"] = int(s["adopter"] not in ("None_Academic", "None_Advisory_Rejected", "International_Agency"))
        out.append(s)
    write("population_roles.csv", list(out[0]), out)
    summary = {}
    for s in out:
        k = (s["sponsor_spec_a"], s["adopted_by_state_body"])
        summary[k] = summary.get(k, 0) + 1
    srows = [{"sponsor_spec_a": k[0], "adopted_by_state_body": k[1], "studies": v} for k, v in sorted(summary.items())]
    write("population_roles_summary.csv", ["sponsor_spec_a", "adopted_by_state_body", "studies"], srows)
    return out


if __name__ == "__main__":
    g = common_scale()
    sf, ar = stock_flow()
    lo = aggregation()
    ro = roles()
    for r in g:
        print(f"{r['group']:<40} n={r['rows']:>3} units={r['units']:>2} over={r['forecast_above_actual']:>3} "
              f"median ratio={r['median_ratio']:.3f} typical factor={r['median_abs_log_factor']:.3f}")
    for r in sf:
        print(r)
    for r in ar:
        print(f"{r['quantity']:<55} {r['value']:.3f}")
    for r in lo[:4]:
        print(r)
    print(len(ro), "population studies in the role ledger")
