"""Rebuild the derived data used on the page from the files in ../sources and ../data.

Run from the package root:  python3 scripts/build_data.py
Requires: openpyxl
Outputs:  data/core_y2027_directions.csv, data/core_y2027_border_premium.csv
"""
import csv, collections, openpyxl, pathlib

ROOT = pathlib.Path(__file__).resolve().parent.parent
SRC, DATA = ROOT / "sources", ROOT / "data"
H, SPLIT = 8760, 0.8  # MWh per MW over 2027 (35,040 quarter-hours x 0.25 h); yearly splitting factor

wb = openpyxl.load_workbook(SRC / "JAO_CORE-Y-BASE-270101-01_results.xlsx", data_only=True)
rows = list(wb["Publication by border"].iter_rows(values_only=True))[1:]
bids = list(wb["Anonymized bids"].iter_rows(values_only=True))[1:]
nbids = collections.Counter(b[0] for b in bids)

fx = openpyxl.load_workbook(SRC / "JAO_EEX_Cal27_base_futures_2026-12-02.xlsx", data_only=True).worksheets[0]
hdr, val = [list(r) for r in fx.iter_rows(values_only=True)][:2]
F = dict(zip(hdr, val))  # Cal-27 base futures, EUR/MWh, per zone

with open(DATA / "atc_benchmark_annex1_yearly.csv") as f:
    bench_pre = {r["direction"]: int(r["yearly_benchmark_pre_split_MW"]) for r in csv.DictReader(f)}

out = []
for b, _, _, req, mw, p in rows:
    a, z = b.split("-")
    bench = round(bench_pre[b] * SPLIT)
    out.append(dict(direction=b, requested_MW=req, allocated_MW=mw, price_EUR_MWh=p,
                    futures_gap_in_minus_out=round(F[z] - F[a], 2), benchmark_post_split_MW=bench,
                    change_vs_benchmark_pct=round(100 * (mw - bench) / bench, 1), n_bids=nbids[b],
                    hedge_floor_EUR_MWh=round(F[z] - F[a] - p, 2) if F[z] > F[a] else "",
                    implied_payment_EUR=round(mw * p * H)))
out.sort(key=lambda r: r["direction"])
with open(DATA / "core_y2027_directions.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=out[0].keys()); w.writeheader(); w.writerows(out)

# ACER-style forward premium per border: (P_AB - P_BA - (F_B - F_A)) / |F_B - F_A|, oriented so the gap is positive
P = {r["direction"]: r["price_EUR_MWh"] for r in out}
prem = []
for A, B in sorted({tuple(sorted(d.split("-"))) for d in P}):
    gap = F[B] - F[A]; s = 1 if gap >= 0 else -1
    num = (P[f"{A}-{B}"] - P[f"{B}-{A}"]) * s - abs(gap)
    prem.append(dict(border=f"{A}-{B}", price_AB=P[f"{A}-{B}"], price_BA=P[f"{B}-{A}"], futures_gap_B_minus_A=round(gap, 2),
                     premium_pct=round(100 * num / abs(gap), 1) if abs(gap) >= 1 else ""))
with open(DATA / "core_y2027_border_premium.csv", "w", newline="") as f:
    w = csv.DictWriter(f, fieldnames=prem[0].keys()); w.writeheader(); w.writerows(prem)

tot = sum(r["allocated_MW"] for r in out)
print(f"{len(out)} directions, {tot} MW allocated, {sum(r['benchmark_post_split_MW'] for r in out)} MW benchmark, "
      f"EUR {sum(r['implied_payment_EUR'] for r in out)/1e9:.2f} bn implied payment")
