#!/usr/bin/env python3
"""Aeolipile dry-lab kernel, ABI 100. Reference runtime.

Standard library only: runs under `python3 -I`.
The JavaScript kernel (web/assets/js/aeo-core.js) and the C11 kernel
(native/aeo_core.c) repeat every arithmetic statement of `run` in the same
order. A change here that is not mirrored there breaks bit-level parity,
which `tools/parity.py` reports as a mismatch.
"""

import math
import re
import struct

AEO_ABI_VERSION = 100
AEO_HOURS = 8760

AEO_OK = 0
AEO_ERR_ABI = -1
AEO_ERR_NON_FINITE = -2
AEO_ERR_BOUND = -3
AEO_ERR_QUORUM = -4
AEO_ERR_SHAPE = -5

LOCUS_CFG = 0
LOCUS_SHAPE = 500000

# 1 MWh of electricity is 3.412142 MMBtu. A heat rate below it claims a
# thermal efficiency above 100 percent.
MMBTU_PER_MWH = 3.412142

# name, low, high, low bound is exclusive, value must be an integer, default
CFG_FIELDS = (
    ("it_load_mw", 0.0, 1e5, True, False, 50.0),
    ("pue_base", 1.0, 3.0, False, False, 1.18),
    ("pue_temp_slope", 0.0, 0.2, False, False, 0.008),
    ("solar_cap_mw", 0.0, 1e6, False, False, 120.0),
    ("wind_cap_mw", 0.0, 1e6, False, False, 80.0),
    ("bess_energy_mwh", 0.0, 1e7, False, False, 200.0),
    ("bess_power_mw", 0.0, 1e6, False, False, 50.0),
    ("bess_rte", 0.0, 1.0, True, False, 0.88),
    ("bess_fade_per_efc", 0.0, 0.01, False, False, 0.00005),
    ("gas_cap_mw", 0.0, 1e6, False, False, 0.0),
    ("gas_heat_rate_mmbtu_mwh", MMBTU_PER_MWH, 30.0, False, False, 7.0),
    ("gas_price_usd_mmbtu", 0.0, 1000.0, False, False, 4.0),
    ("gas_vom_usd_mwh", 0.0, 1000.0, False, False, 3.0),
    ("grid_import_cap_mw", 0.0, 1e6, False, False, 70.0),
    ("forced_curtailment", 0.0, 1.0, False, False, 0.05),
    ("lmp_multiplier", 0.0, 100.0, False, False, 1.0),
    ("capex_usd_million", 0.0, 1e7, False, False, 380.0),
    ("fixed_opex_usd_m_yr", 0.0, 1e6, False, False, 9.5),
    ("discount_rate", 0.0, 0.5, False, False, 0.07),
    ("project_years", 1.0, 100.0, False, True, 20.0),
    ("grid_delay_months", 0.0, 600.0, False, True, 12.0),
    ("voll_usd_mwh", 0.0, 1e6, False, False, 10000.0),
    ("dunkel_start_hour", -1.0, 8759.0, False, True, -1.0),
    ("dunkel_hours", 0.0, 8760.0, False, True, 0.0),
    ("dunkel_lmp_adder_usd", 0.0, 1e5, False, False, 0.0),
    ("heat_start_hour", -1.0, 8759.0, False, True, -1.0),
    ("heat_hours", 0.0, 8760.0, False, True, 0.0),
    ("heat_delta_c", 0.0, 40.0, False, False, 0.0),
)
CFG_NAMES = tuple(f[0] for f in CFG_FIELDS)
CFG_N = len(CFG_FIELDS)

# name, low, high
SERIES_FIELDS = (
    ("solar_cf", 0.0, 1.0),
    ("wind_cf", 0.0, 1.0),
    ("lmp_usd", -1e4, 1e5),
    ("ambient_c", -90.0, 70.0),
)
SERIES_NAMES = tuple(s[0] for s in SERIES_FIELDS)
COHORT_HEADER = ",".join(SERIES_NAMES)

RESULT_NAMES = (
    "total_load_mwh",
    "mean_pue",
    "peak_load_mw",
    "renewable_gen_mwh",
    "renewable_direct_mwh",
    "curtailed_mwh",
    "curtailment_ratio",
    "bess_charge_mwh",
    "bess_discharge_mwh",
    "bess_efc",
    "bess_capacity_end_frac",
    "gas_gen_mwh",
    "gas_fuel_mmbtu",
    "grid_import_mwh",
    "lole_hours",
    "eens_mwh",
    "cfe_hourly_match",
    "grid_cost_usd",
    "gas_cost_usd",
    "annualized_capex_usd",
    "lcoe_usd_mwh",
    "adj_cost_usd_mwh",
    "max_balance_residual_mwh",
)
RES_N = len(RESULT_NAMES)

HOURLY_NAMES = ("load_mw", "ren_direct_mw", "bess_out_mw", "grid_mw", "gas_mw",
                "curtailed_mw", "unserved_mw", "soc_mwh", "price_usd")

FNV_OFFSET_64 = 0xCBF29CE484222325
FNV_PRIME_64 = 0x100000001B3
MASK_64 = 0xFFFFFFFFFFFFFFFF

_NUM_RE = re.compile(r"^-?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$")


def fnv1a64(acc, payload):
    for b in payload:
        acc ^= b
        acc = (acc * FNV_PRIME_64) & MASK_64
    return acc


def quantize(x):
    """Trace quantum: micro-units, half away from zero for the non-negative
    values the trace carries. One multiply, one add, one floor, so every
    runtime lands on the same double."""
    return float(math.floor(x * 1e6 + 0.5))


def default_config():
    return {f[0]: f[5] for f in CFG_FIELDS}


def config_to_wire(cfg):
    """Returns (code, locus, wire). Missing keys take defaults. Unknown keys
    are an ABI error because a silently ignored input is a wrong answer."""
    for key in cfg:
        if key not in CFG_NAMES:
            return AEO_ERR_ABI, 0, None
    wire = []
    for i, f in enumerate(CFG_FIELDS):
        v = cfg.get(f[0], f[5])
        if isinstance(v, bool) or not isinstance(v, (int, float)):
            return AEO_ERR_NON_FINITE, LOCUS_CFG + i, None
        wire.append(float(v))
    return AEO_OK, 0, wire


def validate(wire, series):
    if len(wire) != CFG_N or len(series) != len(SERIES_FIELDS):
        return AEO_ERR_ABI, 0
    for i, f in enumerate(CFG_FIELDS):
        v = wire[i]
        if not math.isfinite(v):
            return AEO_ERR_NON_FINITE, LOCUS_CFG + i
        if v < f[1] or v > f[2] or (f[3] and v <= f[1]):
            return AEO_ERR_BOUND, LOCUS_CFG + i
        if f[4] and math.floor(v) != v:
            return AEO_ERR_SHAPE, LOCUS_CFG + i
    for s in range(len(SERIES_FIELDS)):
        if len(series[s]) != AEO_HOURS:
            return AEO_ERR_SHAPE, LOCUS_SHAPE + s
    for h in range(AEO_HOURS):
        for s, f in enumerate(SERIES_FIELDS):
            v = series[s][h]
            if not math.isfinite(v):
                return AEO_ERR_NON_FINITE, (s + 1) * 100000 + h
            if v < f[1] or v > f[2]:
                return AEO_ERR_BOUND, (s + 1) * 100000 + h
    return AEO_OK, 0


def run(wire, series, hourly=None):
    """Runs the 8,760-hour dispatch. Returns a dict with `code` and `locus`,
    and on success `result` (RES_N doubles), `trace` and `digest`.
    `hourly`, when a list, receives one tuple per hour in HOURLY_NAMES order."""
    code, locus = validate(wire, series)
    if code != AEO_OK:
        return {"code": code, "locus": locus}

    (it, pue_base, pue_slope, solar_cap, wind_cap, e0, p_bess, rte, fade,
     gas_cap, heat_rate, gas_price, gas_vom, grid_cap, forced, lmp_mult,
     capex_m, opex_m, rate, years, delay_m, voll,
     dk_start, dk_hours, dk_adder, ht_start, ht_hours, ht_delta) = wire
    solar, wind, lmp, temp = series

    eta = math.sqrt(rte)
    mc_gas = heat_rate * gas_price + gas_vom
    bess_on = e0 > 0.0 and p_bess > 0.0
    soc = 0.5 * e0
    dis_internal = 0.0
    efc = 0.0
    cap_frac = 1.0
    dk_end = dk_start + dk_hours
    ht_end = ht_start + ht_hours

    total_load = 0.0
    pue_sum = 0.0
    peak = 0.0
    ren_gen = 0.0
    ren_direct = 0.0
    curtailed = 0.0
    chg_sum = 0.0
    dis_sum = 0.0
    gas_sum = 0.0
    gas_fuel = 0.0
    grid_sum = 0.0
    grid_cost = 0.0
    gas_cost = 0.0
    lole = 0.0
    eens = 0.0
    cfe = 0.0
    max_resid = 0.0
    trace = FNV_OFFSET_64

    for h in range(AEO_HOURS):
        dunkel = dk_start >= 0.0 and h >= dk_start and h < dk_end
        heat = ht_start >= 0.0 and h >= ht_start and h < ht_end

        t = temp[h]
        if heat:
            t = t + ht_delta
        excess = t - 20.0
        if excess < 0.0:
            excess = 0.0
        pue = pue_base + pue_slope * excess
        load = it * pue

        s = solar[h]
        w = wind[h]
        if dunkel:
            s = 0.0
            w = 0.0
        price = lmp[h] * lmp_mult
        if dunkel:
            price = price + dk_adder

        gen_s = solar_cap * s
        gen_w = wind_cap * w
        raw = gen_s + gen_w
        forced_mwh = raw * forced
        avail = raw - forced_mwh
        direct = load if load < avail else avail
        surplus = avail - direct
        deficit = load - direct

        chg = 0.0
        if bess_on:
            e_cap = e0 * cap_frac
            if soc > e_cap:
                soc = e_cap
            if surplus > 0.0:
                headroom = e_cap - soc
                lim = headroom / eta
                chg = surplus
                if p_bess < chg:
                    chg = p_bess
                if lim < chg:
                    chg = lim
                stored = chg * eta
                soc = soc + stored
        spill = surplus - chg
        curt = forced_mwh + spill

        bout = 0.0
        if bess_on and deficit > 0.0:
            avail_out = soc * eta
            bout = deficit
            if p_bess < bout:
                bout = p_bess
            if avail_out < bout:
                bout = avail_out
            drawn = bout / eta
            soc = soc - drawn
            if soc < 0.0:
                soc = 0.0
            dis_internal = dis_internal + drawn
            deficit = deficit - bout
            efc = dis_internal / e0
            wear = fade * efc
            cap_frac = 1.0 - wear
            if cap_frac < 0.6:
                cap_frac = 0.6

        grid = 0.0
        gas = 0.0
        if price <= mc_gas:
            grid = deficit if deficit < grid_cap else grid_cap
            deficit = deficit - grid
            gas = deficit if deficit < gas_cap else gas_cap
            deficit = deficit - gas
        else:
            gas = deficit if deficit < gas_cap else gas_cap
            deficit = deficit - gas
            grid = deficit if deficit < grid_cap else grid_cap
            deficit = deficit - grid
        unserved = deficit
        if unserved < 0.0:
            unserved = 0.0
        if unserved > 1e-9:
            lole = lole + 1.0
            eens = eens + unserved

        total_load = total_load + load
        pue_sum = pue_sum + pue
        if load > peak:
            peak = load
        ren_gen = ren_gen + raw
        ren_direct = ren_direct + direct
        curtailed = curtailed + curt
        chg_sum = chg_sum + chg
        dis_sum = dis_sum + bout
        gas_sum = gas_sum + gas
        fuel = gas * heat_rate
        gas_fuel = gas_fuel + fuel
        grid_sum = grid_sum + grid
        cost_g = grid * price
        grid_cost = grid_cost + cost_g
        cost_f = gas * mc_gas
        gas_cost = gas_cost + cost_f
        matched = direct + bout
        cfe = cfe + matched

        supplied = matched + grid
        supplied = supplied + gas
        supplied = supplied + unserved
        resid = load - supplied
        if resid < 0.0:
            resid = -resid
        if resid > max_resid:
            max_resid = resid

        trace = fnv1a64(trace, struct.pack(
            "<5d", quantize(soc), quantize(grid), quantize(gas),
            quantize(curt), quantize(unserved)))
        if hourly is not None:
            hourly.append((load, direct, bout, grid, gas, curt, unserved, soc, price))

    growth = 1.0
    for _ in range(int(years)):
        growth = growth * (1.0 + rate)
    if rate == 0.0:
        crf = 1.0 / years
    else:
        num = rate * growth
        den = growth - 1.0
        crf = num / den
    capex_usd = capex_m * 1e6
    ann_capex = capex_usd * crf
    opex_usd = opex_m * 1e6
    monthly = rate / 12.0
    carry = 1.0
    for _ in range(int(delay_m)):
        carry = carry * (1.0 + monthly)
    served = total_load - eens
    if served < 1e-9:
        served = 1e-9
    cost = ann_capex + opex_usd
    cost = cost + grid_cost
    cost = cost + gas_cost
    lcoe = cost / served
    delayed = ann_capex * carry
    penalty = eens * voll
    adj = delayed + opex_usd
    adj = adj + grid_cost
    adj = adj + gas_cost
    adj = adj + penalty
    adj_cost = adj / served

    curt_ratio = curtailed / ren_gen if ren_gen > 0.0 else 0.0
    result = [
        total_load,
        pue_sum / float(AEO_HOURS),
        peak,
        ren_gen,
        ren_direct,
        curtailed,
        curt_ratio,
        chg_sum,
        dis_sum,
        efc,
        cap_frac,
        gas_sum,
        gas_fuel,
        grid_sum,
        lole,
        eens,
        cfe / total_load,
        grid_cost,
        gas_cost,
        ann_capex,
        lcoe,
        adj_cost,
        max_resid,
    ]
    digest = fnv1a64(FNV_OFFSET_64, struct.pack("<%dd" % RES_N, *result))
    return {
        "code": AEO_OK,
        "locus": 0,
        "result": result,
        "trace": "0x%016x" % trace,
        "digest": "0x%016x" % digest,
    }


def result_dict(out):
    return dict(zip(RESULT_NAMES, out["result"]))


def parse_number(token):
    """Strict decimal grammar shared by every runtime. Python's float() also
    accepts `1_0`, `nan` and `infinity`, which JavaScript and C read
    differently, so anything outside the grammar becomes NaN and fails closed."""
    if _NUM_RE.match(token) is None:
        return float("nan")
    return float(token)


def parse_cohort_csv(raw):
    """Parses AEOLIPILE-COHORT-8760-V1 bytes. Returns (code, locus, series).
    Lines starting with `#` are metadata. The first other line must be the
    header. Row count and values are checked by `validate`."""
    text = raw.decode("utf-8")
    series = [[], [], [], []]
    seen_header = False
    for line in text.split("\n"):
        if line.endswith("\r"):
            line = line[:-1]
        if line == "" or line.startswith("#"):
            continue
        if not seen_header:
            if line != COHORT_HEADER:
                return AEO_ERR_SHAPE, LOCUS_SHAPE, None
            seen_header = True
            continue
        cells = line.split(",")
        if len(cells) != 4:
            return AEO_ERR_SHAPE, LOCUS_SHAPE + 4, None
        for s in range(4):
            series[s].append(parse_number(cells[s]))
    if not seen_header:
        return AEO_ERR_SHAPE, LOCUS_SHAPE, None
    return AEO_OK, 0, series


def describe_locus(code, locus):
    if code == AEO_OK:
        return "ok"
    if code == AEO_ERR_ABI:
        return "abi"
    if locus >= LOCUS_SHAPE:
        idx = locus - LOCUS_SHAPE
        return "shape:%s" % (SERIES_NAMES[idx] if idx < 4 else "row")
    if locus >= 100000:
        return "%s[%d]" % (SERIES_NAMES[locus // 100000 - 1], locus % 100000)
    return "cfg:%s" % CFG_NAMES[locus]


# Stress scan. A threshold is the smallest scanned value of one config field
# at which a result metric first exceeds the ceiling. The scan is a fixed
# grid followed by bisection so that every runtime visits the same points.
SCAN_STEPS = 40
BISECT_STEPS = 30


def _metric(wire, series, field_index, value, metric_index):
    probe = list(wire)
    probe[field_index] = value
    out = run(probe, series)
    if out["code"] != AEO_OK:
        return None
    return out["result"][metric_index]


def find_threshold(wire, series, field, lo, hi, ceiling, metric="adj_cost_usd_mwh"):
    fi = CFG_NAMES.index(field)
    mi = RESULT_NAMES.index(metric)
    integer = CFG_FIELDS[fi][4]
    base = _metric(wire, series, fi, wire[fi], mi)
    out = {"field": field, "metric": metric, "ceiling": ceiling, "lo": lo, "hi": hi,
           "base_value": wire[fi], "base_metric": base, "status": "NO_CROSSING",
           "threshold": None}
    if integer:
        prev = None
        v = lo
        while v <= hi:
            m = _metric(wire, series, fi, v, mi)
            if m is None:
                out["status"] = "FAIL_CLOSED"
                return out
            if m > ceiling:
                out["status"] = "ALREADY_BROKEN" if prev is None else "BREAKS"
                out["threshold"] = v
                return out
            prev = v
            v = v + 1.0
        return out
    span = hi - lo
    prev_x = lo
    m0 = _metric(wire, series, fi, lo, mi)
    if m0 is None:
        out["status"] = "FAIL_CLOSED"
        return out
    if m0 > ceiling:
        out["status"] = "ALREADY_BROKEN"
        out["threshold"] = lo
        return out
    for i in range(1, SCAN_STEPS + 1):
        x = lo + span * i / SCAN_STEPS
        m = _metric(wire, series, fi, x, mi)
        if m is None:
            out["status"] = "FAIL_CLOSED"
            return out
        if m > ceiling:
            a = prev_x
            b = x
            for _ in range(BISECT_STEPS):
                mid = (a + b) / 2.0
                mm = _metric(wire, series, fi, mid, mi)
                if mm is not None and mm > ceiling:
                    b = mid
                else:
                    a = mid
            out["status"] = "BREAKS"
            out["threshold"] = b
            return out
        prev_x = x
    return out
