"""Replay the public, synthetic Power Decision Lab. Python 3.9+, standard library."""
import argparse
import csv
import json
import math
import sqlite3
from datetime import datetime
from pathlib import Path

HERE = Path(__file__).resolve().parent
CASES = ("base", "basis", "gap")
DELIVERY = 12
FEE = 300
DEFAULT_STRIKE = 48
DEFAULT_ESA = 80

def load_day(case="base"):
    if case not in CASES:
        raise ValueError("Unknown case")
    with (HERE / "raw.csv").open(newline="", encoding="utf-8") as f:
        feed = list(csv.DictReader(f))
    inputs, revisions, identities, ids = [], {}, {}, set()
    duplicates = converted = 0
    for r in feed:
        stamp, series, unit = r["hour_utc"], r["series"], r["unit"]
        dt = datetime.strptime(stamp, "%Y-%m-%dT%H:%M:%SZ")
        if dt.date().isoformat() != "2026-06-21" or dt.minute or dt.second:
            raise ValueError("Expected hourly UTC fixture")
        if series not in ("load", "generation", "load_zone", "gen_node"):
            raise ValueError("Unknown series")
        energy = series in ("load", "generation")
        if unit not in (("MWh", "kWh") if energy else ("USD/MWh",)):
            raise ValueError("Unexpected unit")
        if case == "gap" and series == "gen_node" and dt.hour == 13:
            continue
        v, rev, rid = float(r["value"]), int(r["revision"]), int(r["record_id"])
        if not math.isfinite(v) or (energy and v < 0) or rev < 1 or rid in ids:
            raise ValueError("Invalid input or repeated record identifier")
        ids.add(rid)
        if case == "basis" and series == "gen_node":
            v -= 15
        k = (stamp, series, rev)
        if k in revisions:
            if revisions[k] != (unit, v):
                raise ValueError("Conflicting values at the same revision: " + str(k))
            duplicates += 1
        revisions[k] = (unit, v)
        identities.setdefault((stamp, series), set()).add(rev)
        converted += unit == "kWh"
        inputs.append((rid, stamp, series, rev, unit, v))
    with sqlite3.connect(":memory:") as db:
        db.row_factory = sqlite3.Row
        db.execute("CREATE TABLE raw(record_id INTEGER, hour_utc TEXT, series TEXT, revision INTEGER, unit TEXT, value REAL)")
        db.executemany("INSERT INTO raw VALUES(?,?,?,?,?,?)", inputs)
        hourly = [dict(r) for r in db.execute((HERE / "hourly.sql").read_text(encoding="utf-8"))]
    if any(r[k] is None for r in hourly for k in ("load", "gen", "zone")):
        raise ValueError("Missing required meter, generation, or site price")
    audit = dict(raw=len(inputs), duplicates=duplicates,
                 superseded=sum(len(s)-1 for s in identities.values()), converted=converted,
                 priced=sum(r["node"] is not None for r in hourly))
    return {"hours": hourly, "audit": audit}

def compare(day, strike=DEFAULT_STRIKE, esa=DEFAULT_ESA):
    if not all(math.isfinite(v) for v in (strike, esa)):
        raise ValueError("Prices must be finite")
    rows = day["hours"]
    load, gen = sum(r["load"] for r in rows), sum(r["gen"] for r in rows)
    matched = sum(min(r["load"], r["gen"]) for r in rows)
    utility = sum(r["load"]*(r["zone"]+DELIVERY) for r in rows)
    active = [r for r in rows if r["gen"] > 0]
    complete = all(r["node"] is not None for r in active)
    revenue = sum(r["gen"]*r["node"] for r in active) if complete else None
    receipt = revenue - strike*gen if complete else None
    return dict(load=load, gen=gen, matched=matched, match=matched/load if load else None,
                utility=utility, esa=load*esa+FEE, receipt=receipt,
                ppa=utility-receipt if complete else None,
                capture=revenue/gen if complete and gen else None)

def capacity(firm, reserve, pue, target):
    if not all(math.isfinite(x) for x in (firm, reserve, pue, target)) or min(firm, reserve, target)<0 or pue<1:
        raise ValueError("Invalid capacity inputs")
    it = max(0, firm-reserve)/pue
    return {"it":it, "overhead":it*(pue-1), "margin":it-target}

if __name__ == "__main__":
    p = argparse.ArgumentParser(description=__doc__)
    p.add_argument("--case", choices=CASES, default="base")
    p.add_argument("--strike", type=float, default=DEFAULT_STRIKE)
    p.add_argument("--esa", type=float, default=DEFAULT_ESA)
    p.add_argument("--snapshot", action="store_true", help="Print all cleaned scenarios used by the website")
    p.add_argument("--hours", action="store_true", help="Include the 24 aligned hourly records")
    p.add_argument("--capacity", nargs=4, type=float, metavar=("FIRM_MW","RESERVE_MW","PUE","TARGET_IT_MW"))
    args = p.parse_args()
    if args.snapshot:
        out = {"terms":dict(strike=DEFAULT_STRIKE, esa=DEFAULT_ESA, fee=FEE, delivery=DELIVERY),
               "cases":{k:load_day(k) for k in CASES}}
    elif args.capacity:
        out = capacity(*args.capacity)
    else:
        day = load_day(args.case)
        out = {"case":args.case, "audit":day["audit"], "results":compare(day,args.strike,args.esa)}
        if args.hours:
            out["hours"] = day["hours"]
    print(json.dumps(out, indent=2, allow_nan=False))
