#!/usr/bin/env python3
"""AEO-STRESS-8: the fixed stress suite behind a kernel_run receipt.

A kernel_run receipt records what the signer computed: one base run and
eight stress runs of the kernel on a frozen cohort, and how many of the
eight a set of threshold claims survives. web/assets/js/metried-core.js
builds the same payload byte for byte.
"""

import hashlib
import math
import os
import re
import sys

sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import aeo_core as k  # noqa: E402
import metried_verify as gate  # noqa: E402

SUITE = "AEO-STRESS-8"
MAX_MICRO = 9000000000000000
RECEIPT_METRICS = ("adj_cost_usd_mwh", "lcoe_usd_mwh", "cfe_hourly_match", "eens_mwh",
                   "lole_hours", "curtailment_ratio", "grid_import_mwh")
_NUM_RE = re.compile(r"^-?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?$")
_ID_RE = re.compile(r"^[A-Za-z0-9._-]{1,64}$")

_I = k.CFG_NAMES.index


def _dunkel(w, start):
    w[_I("dunkel_start_hour")] = start
    w[_I("dunkel_hours")] = 72.0
    w[_I("dunkel_lmp_adder_usd")] = 120.0


def _heat(w):
    w[_I("heat_start_hour")] = 4200.0
    w[_I("heat_hours")] = 300.0
    w[_I("heat_delta_c")] = 14.0


def _scaled(w, name, factor, cap):
    v = w[_I(name)] * factor
    w[_I(name)] = cap if v > cap else v


def _added(w, name, amount, cap):
    v = w[_I(name)] + amount
    w[_I(name)] = cap if v > cap else v


def _s1(w):
    _dunkel(w, 200.0)


def _s2(w):
    _dunkel(w, 4400.0)


def _s3(w):
    _heat(w)


def _s4(w):
    _added(w, "forced_curtailment", 0.15, 1.0)


def _s5(w):
    _scaled(w, "lmp_multiplier", 2.0, 100.0)


def _s6(w):
    _scaled(w, "gas_price_usd_mmbtu", 2.0, 1000.0)


def _s7(w):
    _added(w, "grid_delay_months", 24.0, 600.0)


def _s8(w):
    _dunkel(w, 200.0)
    _heat(w)
    _scaled(w, "lmp_multiplier", 2.0, 100.0)


SCENARIOS = (
    ("dunkelflaute_winter_72h", _s1),
    ("dunkelflaute_summer_72h", _s2),
    ("heatwave_300h", _s3),
    ("curtailment_plus_15pt", _s4),
    ("prices_doubled", _s5),
    ("gas_price_doubled", _s6),
    ("grid_delay_plus_24m", _s7),
    ("compound_winter_heat_prices", _s8),
)


def micro(x):
    if not math.isfinite(x):
        return "out_of_range"
    m = math.floor(x * 1e6 + 0.5)
    if m > MAX_MICRO or m < -MAX_MICRO:
        return "out_of_range"
    return int(m)


def parse_config_strings(config):
    """A receipt config is 28 decimal strings, one per ABI field."""
    if not isinstance(config, dict) or sorted(config) != sorted(k.CFG_NAMES):
        raise gate.GateError("AEO-R02", "config must hold exactly the %d ABI fields" % k.CFG_N)
    wire = []
    for name in k.CFG_NAMES:
        text = config[name]
        if not isinstance(text, str) or _NUM_RE.match(text) is None or len(text) > 32:
            raise gate.GateError("AEO-R02", "config.%s must be a decimal string" % name)
        wire.append(float(text))
    return wire


def parse_claims(claims_input):
    if not isinstance(claims_input, list) or not (1 <= len(claims_input) <= gate.MAX_CLAIMS):
        raise gate.GateError("AEO-R02", "between 1 and %d claims are required" % gate.MAX_CLAIMS)
    parsed = []
    for i, c in enumerate(claims_input, start=1):
        if (not isinstance(c, dict) or sorted(c) != ["metric", "op", "value"]
                or c["metric"] not in k.RESULT_NAMES or c["op"] not in ("<=", ">=")
                or not isinstance(c["value"], str) or _NUM_RE.match(c["value"]) is None
                or len(c["value"]) > 32):
            raise gate.GateError("AEO-R02", "claim %d is malformed" % i)
        parsed.append((k.RESULT_NAMES.index(c["metric"]), c["op"], float(c["value"])))
    return parsed


def _holds(result, parsed):
    for mi, op, threshold in parsed:
        v = result[mi]
        if op == "<=":
            if not v <= threshold:
                return False
        elif not v >= threshold:
            return False
    return True


def kernel_run_payload(case_id, config, cohort_id, cohort_raw, claims_input):
    if not isinstance(case_id, str) or _ID_RE.match(case_id) is None:
        raise gate.GateError("AEO-R02", "case_id must be 1 to 64 characters of A-Z a-z 0-9 . _ -")
    if not isinstance(cohort_id, str) or _ID_RE.match(cohort_id) is None:
        raise gate.GateError("AEO-R02", "cohort_id is malformed")
    wire = parse_config_strings(config)
    parsed = parse_claims(claims_input)
    code, locus, series = k.parse_cohort_csv(cohort_raw)
    if code != k.AEO_OK:
        raise gate.GateError("AEO-R02", "cohort failed to parse: %s" % k.describe_locus(code, locus))
    base = k.run(wire, series)
    if base["code"] != k.AEO_OK:
        raise gate.GateError("AEO-R02", "kernel failed closed: code %d at %s"
                             % (base["code"], k.describe_locus(base["code"], base["locus"])))

    claims = []
    claims_passed = 0
    for i, (c, (mi, op, threshold)) in enumerate(zip(claims_input, parsed), start=1):
        v = base["result"][mi]
        ok = (v <= threshold) if op == "<=" else (v >= threshold)
        claims_passed += ok
        claims.append({"id": i, "metric": c["metric"], "op": op, "value": c["value"],
                       "base_micro": micro(v), "base_holds": bool(ok)})

    stress = []
    passes = 0
    for i, (name, apply) in enumerate(SCENARIOS, start=1):
        probe = list(wire)
        apply(probe)
        out = k.run(probe, series)
        if out["code"] != k.AEO_OK:
            raise gate.GateError("AEO-R02", "stress scenario %s failed closed" % name)
        ok = _holds(out["result"], parsed)
        passes += ok
        stress.append({"id": i, "name": name, "holds": bool(ok), "trace": out["trace"],
                       "adj_cost_micro": micro(out["result"][k.RESULT_NAMES.index("adj_cost_usd_mwh")])})

    attempts = len(SCENARIOS)
    bp = gate.wilson_bp(passes, attempts)
    quorum_met = attempts >= gate.QUORUM_MIN_ATTEMPTS and bp[0] >= gate.QUORUM_MIN_LOWER_BP
    if claims_passed < len(claims):
        disposition, rule = "CULLED_CLAIM_FALSE_AT_BASE", "AEO-R03"
    elif not quorum_met:
        disposition, rule = "S2_CAPPED", "AEO-R04"
    else:
        disposition, rule = "S4_VERIFIED", "PASS_ALL"

    return {
        "schema": gate.SCHEMA,
        "kind": "kernel_run",
        "case_id": case_id,
        "disposition": disposition,
        "rule_triggered": rule,
        "run": {
            "abi": k.AEO_ABI_VERSION,
            "cohort_id": cohort_id,
            "cohort_sha256": hashlib.sha256(cohort_raw).hexdigest(),
            "config": {name: config[name] for name in k.CFG_NAMES},
            "trace": base["trace"],
            "digest": base["digest"],
            "metrics_micro": {name: micro(base["result"][k.RESULT_NAMES.index(name)])
                              for name in RECEIPT_METRICS},
        },
        "claims_input": [{"metric": c["metric"], "op": c["op"], "value": c["value"]}
                         for c in claims_input],
        "claims_total": len(claims),
        "claims_passed": int(claims_passed),
        "claims": claims,
        "stress_suite": SUITE,
        "stress": stress,
        "stress_quorum": {
            "source": "kernel_stress_suite",
            "attempts": attempts,
            "passes": int(passes),
            "wilson_ci95_bp": bp,
            "quorum_met": bool(quorum_met),
        },
    }
