"""
Balanced EU MRV panel 2023-2025 and the carbon-intensity results reported in:

  Laos, R.: The Blue-Economy Ambition-Implementation Gap: An Analysis of IMO
  Decarbonization Governance. TransNav (submitted).

Input: the three THETIS-MRV publication files (EMSA, https://mrv.emsa.europa.eu),
placed in ../raw/ with these names (the versions used in the article):

  2023-v91-15082026-EU_MRV_Publication_of_information.xlsx
  2024-v242-12092026-EU_MRV_Publication_of_information.xlsx
  2025-v57-12092026-EU_MRV_Publication_of_information.xlsx

Output:
  ../data/mrv_balanced_panel_2023_2025.csv   one row per ship (6,525 ships)
  ../results/table3_by_ship_type.csv         Table 3 of the article
  ../results/summary_statistics.csv          figures quoted in Section 4.2

Requirements: Python 3.10+, pandas, numpy, scipy, openpyxl.
Run:  python mrv_panel_analysis.py
"""

from pathlib import Path

import numpy as np
import pandas as pd
from scipy.stats import spearmanr

HERE = Path(__file__).resolve().parent
RAW = HERE.parent / "raw"
DATA = HERE.parent / "data"
RESULTS = HERE.parent / "results"

FILES = {
    2023: ("2023-v91-15082026-EU_MRV_Publication_of_information.xlsx", "2023"),
    2024: ("2024-v242-12092026-EU_MRV_Publication_of_information.xlsx", "2024 Full ERs"),
    2025: ("2025-v57-12092026-EU_MRV_Publication_of_information.xlsx", "2025 Full ERs"),
}

# Annual average CO2 emissions per transport work, by denominator.
# The 2023 file and the 2024-2025 files use slightly different column headings.
DENOMINATORS = ["mass", "volume", "dwt", "pax", "freight"]
CI_COLUMNS = {
    2023: {
        "mass": "Annual average CO₂ emissions per transport work (mass) [g CO₂ / m tonnes · n miles]",
        "volume": "Annual average CO₂ emissions per transport work (volume) [g CO₂ / m³ · n miles]",
        "dwt": "Annual average CO₂ emissions per transport work (dwt) [g CO₂ / dwt carried · n miles]",
        "pax": "Annual average CO₂ emissions per transport work (pax) [g CO₂ / pax · n miles]",
        "freight": "Annual average CO₂ emissions per transport work (freight) [g CO₂ / m tonnes · n miles]",
        "hours": "Annual Time spent at sea [hours]",
    },
    2024: {
        "mass": "CO₂ emissions per transport work (mass) [g CO₂ / m tonnes · n miles]",
        "volume": "CO₂ emissions per transport work (volume) [g CO₂ / m³ · n miles]",
        "dwt": "CO₂ emissions per transport work (dwt) [g CO₂ / dwt carried · n miles]",
        "pax": "CO₂ emissions per transport work (pax) [g CO₂ / pax · n miles]",
        "freight": "CO₂ emissions per transport work (freight) [g CO₂ / m tonnes · n miles]",
        "hours": "Time spent at sea [hours]",
    },
}
CI_COLUMNS[2025] = CI_COLUMNS[2024]

YEARS = [2023, 2024, 2025]
TRIM = (0.01, 0.99)          # percentile trimming within ship type and year
MIN_GROUP = 25               # smaller ship types are pooled in Table 3

# CII reduction factors relative to the 2019 reference line (MEPC.338(76)):
# 5% (2023), 7% (2024), 9% (2025)
RF = {2023: 0.05, 2024: 0.07, 2025: 0.09}
REQ_23_24 = ((1 - RF[2024]) / (1 - RF[2023]) - 1) * 100   # -2.1%
REQ_24_25 = ((1 - RF[2025]) / (1 - RF[2024]) - 1) * 100   # -2.2%
REQ_23_25 = ((1 - RF[2025]) / (1 - RF[2023]) - 1) * 100   # -4.2%


def to_num(s):
    return pd.to_numeric(s.astype(str).str.replace(",", "").str.strip(), errors="coerce")


def read_year(year):
    fname, sheet = FILES[year]
    raw = pd.read_excel(RAW / fname, sheet_name=sheet, header=2, dtype=str)
    cols = CI_COLUMNS[year]
    df = pd.DataFrame({
        "imo": raw["IMO Number"].str.strip(),
        "name": raw["Name"],
        "type": raw["Ship type"].str.strip(),
    })
    for key, col in cols.items():
        df[key] = to_num(raw[col])
    return df


def main():
    years = {y: read_year(y) for y in YEARS}

    # 1. Denominator per ship type: the one reported by most ships of that type
    #    (positive values, all three years pooled).
    pooled = pd.concat(years.values())
    majority = pooled.groupby("type")[DENOMINATORS].apply(lambda g: (g > 0).sum().idxmax()).to_dict()

    # 2. In each annual dataset: carbon intensity in the type's denominator,
    #    drop missing/zero values, trim below the 1st and above the 99th
    #    percentile within ship type.
    clean = {}
    for y, df in years.items():
        df = df.copy()
        df["denominator"] = df["type"].map(majority)
        df["ci"] = [row[row["denominator"]] for row in df.to_dict("records")]
        df = df[df["ci"] > 0]
        g = df.groupby("type")["ci"]
        lo, hi = g.transform(lambda s: s.quantile(TRIM[0])), g.transform(lambda s: s.quantile(TRIM[1]))
        clean[y] = df[(df["ci"] >= lo) & (df["ci"] <= hi)].set_index("imo")

    # 3. Balanced panel: ships retained in all three years with the same
    #    transport-work denominator. Ships are classified by their 2023 ship type.
    ids = clean[2023].index.intersection(clean[2024].index).intersection(clean[2025].index)
    p = pd.DataFrame(index=ids)
    p.index.name = "imo_number"
    p["ship_name"] = clean[2023].loc[ids, "name"]
    for y in YEARS:
        p[f"ship_type_{y}"] = clean[y].loc[ids, "type"]
        p[f"denominator_{y}"] = clean[y].loc[ids, "denominator"]
    same_den = (p["denominator_2023"] == p["denominator_2024"]) & (p["denominator_2023"] == p["denominator_2025"])
    p = p[same_den].copy()
    p["ship_type"] = p["ship_type_2023"]
    p["denominator"] = p["denominator_2023"]
    p = p.drop(columns=[f"denominator_{y}" for y in YEARS])
    p["type_changed_after_2023"] = ~((p["ship_type_2023"] == p["ship_type_2024"]) & (p["ship_type_2023"] == p["ship_type_2025"]))
    for y in YEARS:
        p[f"ci_{y}"] = clean[y].loc[p.index, "ci"]
        p[f"hours_at_sea_{y}"] = clean[y].loc[p.index, "hours"]

    # 4. Changes, bands and grouping.
    p["change_2023_24_pct"] = (p["ci_2024"] / p["ci_2023"] - 1) * 100
    p["change_2024_25_pct"] = (p["ci_2025"] / p["ci_2024"] - 1) * 100
    p["change_2023_25_pct"] = (p["ci_2025"] / p["ci_2023"] - 1) * 100
    for y in YEARS:
        # five equal groups within ship type, recalculated for each year (1 = lowest intensity)
        p[f"band_{y}"] = p.groupby("ship_type")[f"ci_{y}"].transform(
            lambda s: pd.qcut(s.rank(method="first"), 5, labels=False) + 1).astype(int)
    counts = p["ship_type"].value_counts()
    table_rows = [t for t in counts.index if counts[t] >= MIN_GROUP and t not in ("Other ship types", "Container/ro-ro cargo ship")]
    p["table3_group"] = np.where(p["ship_type"].isin(table_rows), p["ship_type"], "Other ship types")

    DATA.mkdir(exist_ok=True)
    RESULTS.mkdir(exist_ok=True)
    p.reset_index().to_csv(DATA / "mrv_balanced_panel_2023_2025.csv", index=False, float_format="%.6g")

    # 5. Table 3.
    def row(g):
        return pd.Series({
            "n": len(g),
            "median_change_2023_24_pct": g["change_2023_24_pct"].median(),
            "median_change_2024_25_pct": g["change_2024_25_pct"].median(),
            "ships_moving_gt10pct_in_a_year_pct": ((g["change_2023_24_pct"].abs() > 10).mean()
                                                    + (g["change_2024_25_pct"].abs() > 10).mean()) / 2 * 100,
            "ships_changing_band_2024_25_pct": (g["band_2024"] != g["band_2025"]).mean() * 100,
            "median_hours_at_sea_2025": g["hours_at_sea_2025"].median(),
        })
    t3 = p.groupby("table3_group").apply(row)
    t3 = t3.sort_values("ships_changing_band_2024_25_pct")
    t3 = pd.concat([t3.drop("Other ship types"), t3.loc[["Other ship types"]]])
    t3.loc["All ships in panel"] = row(p)
    t3.loc["Required by reduction factor path", ["median_change_2023_24_pct", "median_change_2024_25_pct"]] = [REQ_23_24, REQ_24_25]
    t3.index.name = "ship_type"
    t3["n"] = t3["n"].astype("Int64")
    t3.round(1).to_csv(RESULTS / "table3_by_ship_type.csv")

    # 6. Summary statistics quoted in Section 4.2.
    def spearman_within_type(a, b):
        rhos, ns = [], []
        for _, g in p.groupby("ship_type"):
            if len(g) >= 3:
                rhos.append(spearmanr(g[a], g[b]).statistic)
                ns.append(len(g))
        return float(np.average(rhos, weights=ns))

    s = {
        "ships_in_panel": len(p),
        "ships_whose_reported_type_changed_after_2023": int(p["type_changed_after_2023"].sum()),
        "median_change_2023_24_pct": p["change_2023_24_pct"].median(),
        "median_change_2024_25_pct": p["change_2024_25_pct"].median(),
        "median_change_2023_25_pct": p["change_2023_25_pct"].median(),
        "required_change_2023_24_pct": REQ_23_24,
        "required_change_2024_25_pct": REQ_24_25,
        "required_change_2023_25_pct": REQ_23_25,
        "share_meeting_required_2023_25_pct": (p["change_2023_25_pct"] <= REQ_23_25).mean() * 100,
        "share_abs_change_gt10pct_2023_24": (p["change_2023_24_pct"].abs() > 10).mean() * 100,
        "share_abs_change_gt10pct_2024_25": (p["change_2024_25_pct"].abs() > 10).mean() * 100,
        "share_abs_change_gt20pct_2023_24": (p["change_2023_24_pct"].abs() > 20).mean() * 100,
        "share_abs_change_gt20pct_2024_25": (p["change_2024_25_pct"].abs() > 20).mean() * 100,
        "share_reversing_direction_pct": ((np.sign(p["change_2023_24_pct"]) * np.sign(p["change_2024_25_pct"])) < 0).mean() * 100,
        "spearman_within_type_2023_24": spearman_within_type("ci_2023", "ci_2024"),
        "spearman_within_type_2024_25": spearman_within_type("ci_2024", "ci_2025"),
        "share_changing_band_2023_24_pct": (p["band_2023"] != p["band_2024"]).mean() * 100,
        "share_changing_band_2024_25_pct": (p["band_2024"] != p["band_2025"]).mean() * 100,
        "share_moving_2plus_bands_2023_24_pct": ((p["band_2023"] - p["band_2024"]).abs() >= 2).mean() * 100,
        "share_moving_2plus_bands_2024_25_pct": ((p["band_2024"] - p["band_2025"]).abs() >= 2).mean() * 100,
        "median_hours_at_sea_2025": p["hours_at_sea_2025"].median(),
    }
    pd.Series(s, name="value").rename_axis("statistic").round(3).to_csv(RESULTS / "summary_statistics.csv")

    print(t3.round(1).to_string())
    print()
    for k, v in s.items():
        print(f"{k:50s} {v:.3f}" if isinstance(v, float) else f"{k:50s} {v}")


if __name__ == "__main__":
    main()
