"""Independent re-implementation of the daily-batch assigned-carbon benchmark from data/raw."""
import gzip, json, glob, sys, collections, datetime
from fractions import Fraction as F
raw = {}
conflicts = 0
for p in sorted(glob.glob(sys.argv[1] + "/data/raw/*.json.gz")):
    for r in json.load(gzip.open(p))["data"]:
        t = datetime.datetime.strptime(r["from"], "%Y-%m-%dT%H:%MZ")
        a = r["intensity"].get("actual")
        if t in raw and raw[t] != a: conflicts += 1
        raw[t] = a
days = collections.defaultdict(dict)
for t, a in raw.items():
    if t.minute % 30: continue
    days[t.date()][t.hour * 2 + t.minute // 30] = a
complete = {d: [v[i] for i in range(48)] for d, v in days.items()
            if len(v) == 48 and all(isinstance(v[i], (int, float)) and v[i] >= 0 for i in range(48))}
print("conflicting duplicates", conflicts)
season = lambda d: {12: 0, 1: 0, 2: 0, 3: 1, 4: 1, 5: 1, 6: 2, 7: 2, 8: 2}.get(d.month, 3)
train = [d for d in complete if d.year == 2023]
print("training days", len(train), {y: sum(1 for d in complete if d.year == y) for y in (2024, 2025)})
def rank(ds):
    m = [F(sum(complete[d][i] for d in ds), len(ds)) for i in range(48)]
    return sorted(range(48), key=lambda i: (m[i], i))
prof = {s: rank([d for d in train if season(d) == s]) for s in range(4)}
annual = rank(train)
def cost(c, x, b):  # x: utilisation per slot
    return sum(F(1, 2) * (b + (1 - b) * xi) * ci for xi, ci in zip(x, c))
out = {}
for y in (2024, 2025):
    ev = sorted(d for d in complete if d.year == y)
    for k in (24, 42, 12, 36):
        u = F(k, 48)
        for b in (F(0), F(1, 2)):
            tot_s = tot_u = tot_a = 0; higher = 0
            for d in ev:
                c = complete[d]
                sel = set(prof[season(d)][:k]); xs = [1 if i in sel else 0 for i in range(48)]
                sa = set(annual[:k]); xa = [1 if i in sa else 0 for i in range(48)]
                cs, cu = cost(c, xs, b), cost(c, [u] * 48, b)
                tot_s += cs; tot_u += cu; tot_a += cost(c, xa, b)
                higher += cs > cu
            print(f"{y} u={float(u)*100:.1f}% idle={float(b):.2f}: seasonal {float(100*(1-tot_s/tot_u)):.6f}%  annual {float(100*(1-tot_a/tot_u)):.4f}%  higher days {higher}/{len(ev)}")
print("absolute assigned-carbon saving vs uniform, zero idle, mean g CO2 per day (1 kW max):")
for y in (2024, 2025):
    ev = sorted(d for d in complete if d.year == y)
    row = []
    for k in (12, 24, 36, 42, 48):
        u = F(k, 48); s = 0
        for d in ev:
            c = complete[d]; sel = set(prof[season(d)][:k])
            s += cost(c, [u] * 48, 0) - cost(c, [1 if i in sel else 0 for i in range(48)], 0)
        row.append(f"u={float(u)*100:.1f}%: {float(s/len(ev)):.0f} g")
    print(y, "; ".join(row))
