#!/usr/bin/env python3
"""METRIED dry-lab evidence gate and offline receipt verifier.

Standard library only: runs under `python3 -I`.

Rules
  AEO-R01  byte anchoring: a claim must match bytes of an active data row.
           Bytes of a line that starts with `#` are assumption shadow.
  AEO-R02  fail closed on malformed input.
  AEO-R04  Wilson 95 percent lower bound: a claim is verified only when at
           least 4 stress attempts ran and the lower bound is 0.50 or more.

Receipts carry integers and strings only. A float prints differently in
Python and JavaScript, and a receipt has to hash to the same bytes in both.

Usage
  python3 -I python/metried_verify.py verify RECEIPT.json [--source FILE] [--pubkey HEX]
                                             [--replay --cohort-dir data/cohorts]
  python3 -I python/metried_verify.py adjudicate --case-id ID --source FILE --claims CLAIMS.json
                                             --stress-passes N --stress-attempts M --seed-file FILE
  python3 -I python/metried_verify.py demo
"""

import hashlib
import json
import math
import os
import sys

SCHEMA = "METRIED-AEOV-V1"
MAX_CLAIMS = 32
Z_95 = 1.959963984540054
QUORUM_MIN_ATTEMPTS = 4
QUORUM_MIN_LOWER_BP = 5000
DEMO_SEED_LABEL = b"aeolipile-metried-demo-seed-v1"

# RFC 8032 Ed25519 over plain integers.
_Q = (1 << 255) - 19
_L = (1 << 252) + 27742317777372353535851937790883648493


def _inv(x):
    return pow(x, _Q - 2, _Q)


_D = (-121665 * _inv(121666)) % _Q
_I = pow(2, (_Q - 1) // 4, _Q)


def _xrecover(y):
    xx = (y * y - 1) * _inv(_D * y * y + 1) % _Q
    x = pow(xx, (_Q + 3) // 8, _Q)
    if (x * x - xx) % _Q != 0:
        x = (x * _I) % _Q
    if x % 2 != 0:
        x = _Q - x
    return x


_BY = (4 * _inv(5)) % _Q
_BX = _xrecover(_BY)
_B = (_BX, _BY, 1, (_BX * _BY) % _Q)
_ID = (0, 1, 1, 0)


def _pt_add(p, q):
    a = ((p[1] - p[0]) * (q[1] - q[0])) % _Q
    b = ((p[1] + p[0]) * (q[1] + q[0])) % _Q
    c = (2 * p[3] * q[3] * _D) % _Q
    d = (2 * p[2] * q[2]) % _Q
    e, f, g, h = (b - a) % _Q, (d - c) % _Q, (d + c) % _Q, (b + a) % _Q
    return ((e * f) % _Q, (g * h) % _Q, (f * g) % _Q, (e * h) % _Q)


def _pt_mul(s, p):
    q = _ID
    while s > 0:
        if s & 1:
            q = _pt_add(q, p)
        p = _pt_add(p, p)
        s >>= 1
    return q


def _pt_encode(p):
    zi = _inv(p[2])
    x = (p[0] * zi) % _Q
    y = (p[1] * zi) % _Q
    return (y | ((x & 1) << 255)).to_bytes(32, "little")


def _pt_decode(b):
    if len(b) != 32:
        return None
    val = int.from_bytes(b, "little")
    sign = (val >> 255) & 1
    y = val & ((1 << 255) - 1)
    if y >= _Q:
        return None
    xx = ((y * y - 1) * _inv(_D * y * y + 1)) % _Q
    if xx == 0:
        if sign:
            return None
        x = 0
    else:
        x = pow(xx, (_Q + 3) // 8, _Q)
        if (x * x - xx) % _Q != 0:
            x = (x * _I) % _Q
            if (x * x - xx) % _Q != 0:
                return None
        if (x & 1) != sign:
            x = _Q - x
    return (x, y, 1, (x * y) % _Q)


def _clamp(seed32):
    h = hashlib.sha512(seed32).digest()
    a = int.from_bytes(h[:32], "little")
    a &= (1 << 254) - 8
    a |= 1 << 254
    return a, h[32:]


def ed25519_pubkey(seed32):
    a, _ = _clamp(seed32)
    return _pt_encode(_pt_mul(a, _B))


def ed25519_sign(seed32, msg):
    a, prefix = _clamp(seed32)
    pub = _pt_encode(_pt_mul(a, _B))
    r = int.from_bytes(hashlib.sha512(prefix + msg).digest(), "little") % _L
    big_r = _pt_encode(_pt_mul(r, _B))
    k = int.from_bytes(hashlib.sha512(big_r + pub + msg).digest(), "little") % _L
    s = (r + k * a) % _L
    return big_r + s.to_bytes(32, "little")


def ed25519_verify(pubkey, msg, sig):
    if len(pubkey) != 32 or len(sig) != 64:
        return False
    a = _pt_decode(pubkey)
    r = _pt_decode(sig[:32])
    s = int.from_bytes(sig[32:], "little")
    if a is None or r is None or s >= _L:
        return False
    k = int.from_bytes(hashlib.sha512(sig[:32] + pubkey + msg).digest(), "little") % _L
    return _pt_encode(_pt_mul(s, _B)) == _pt_encode(_pt_add(r, _pt_mul(k, a)))


def demo_seed():
    """A published seed. Receipts signed with it prove integrity, not origin."""
    return hashlib.sha256(DEMO_SEED_LABEL).digest()


class GateError(ValueError):
    def __init__(self, rule, message):
        super().__init__("[%s] %s" % (rule, message))
        self.rule = rule


def fnv1a64_hex(data):
    h = 0xCBF29CE484222325
    for b in data:
        h ^= b
        h = (h * 0x100000001B3) & 0xFFFFFFFFFFFFFFFF
    return "0x%016x" % h


def _check_canonical(value, path="$"):
    if value is None or isinstance(value, (bool, str)):
        return
    if isinstance(value, int):
        if abs(value) > 9007199254740991:
            raise GateError("AEO-R02", "integer beyond 2^53 at %s" % path)
        return
    if isinstance(value, list):
        for i, item in enumerate(value):
            _check_canonical(item, "%s[%d]" % (path, i))
        return
    if isinstance(value, dict):
        for key, item in value.items():
            if not isinstance(key, str):
                raise GateError("AEO-R02", "non-string key at %s" % path)
            _check_canonical(item, "%s.%s" % (path, key))
        return
    raise GateError("AEO-R02", "%s is not allowed in a receipt at %s" % (type(value).__name__, path))


def canonical_preimage(payload):
    _check_canonical(payload)
    body = json.dumps(payload, sort_keys=True, separators=(",", ":"), ensure_ascii=False)
    return (SCHEMA + "\n" + body).encode("utf-8")


def wilson_bp(passes, attempts):
    """Wilson 95 percent interval in basis points, rounded half up."""
    if attempts <= 0:
        return [0, 0]
    p = passes / attempts
    z2 = Z_95 * Z_95
    denom = 1.0 + z2 / attempts
    center = (p + z2 / (2.0 * attempts)) / denom
    half = (Z_95 * math.sqrt((p * (1.0 - p) + z2 / (4.0 * attempts)) / attempts)) / denom
    lo = center - half
    hi = center + half
    if lo < 0.0:
        lo = 0.0
    if hi > 1.0:
        hi = 1.0
    return [int(math.floor(lo * 10000.0 + 0.5)), int(math.floor(hi * 10000.0 + 0.5))]


def split_active_shadow(source):
    active = bytearray(source)
    shadow = bytearray(b" " * len(source))
    in_comment = False
    for i, b in enumerate(source):
        if b == 0x23 and (i == 0 or source[i - 1] == 0x0A):
            in_comment = True
        if in_comment:
            active[i] = 0x20
            shadow[i] = b
        if b == 0x0A:
            in_comment = False
    return bytes(active), bytes(shadow)


def sweep_claims(source, claims):
    if not isinstance(claims, list) or len(claims) == 0 or len(claims) > MAX_CLAIMS:
        raise GateError("AEO-R02", "between 1 and %d claims are required" % MAX_CLAIMS)
    active, shadow = split_active_shadow(source)
    results = []
    passed = 0
    for idx, claim in enumerate(claims, start=1):
        metric = claim.get("metric") if isinstance(claim, dict) else None
        needle_text = claim.get("needle") if isinstance(claim, dict) else None
        if not isinstance(metric, str) or not isinstance(needle_text, str) or needle_text == "":
            raise GateError("AEO-R02", "claim %d needs a metric and a non-empty needle" % idx)
        needle = needle_text.encode("utf-8")
        pos_active = active.find(needle)
        pos_shadow = shadow.find(needle)
        entry = {"id": idx, "metric": metric, "needle": needle_text,
                 "byte_span": [-1, -1], "shadow_offset": -1}
        if pos_active != -1:
            passed += 1
            entry["byte_span"] = [pos_active, pos_active + len(needle)]
            entry["status"] = "PASS"
        elif pos_shadow != -1:
            entry["shadow_offset"] = pos_shadow
            entry["status"] = "FAIL_INACTIVE_ASSUMPTION_COMMENT"
        else:
            entry["status"] = "FAIL_MISSING_ANCHOR"
        results.append(entry)
    return results, passed, fnv1a64_hex(active)


def decide(claims_total, claims_passed, attempts, lower_bp):
    quorum_met = attempts >= QUORUM_MIN_ATTEMPTS and lower_bp >= QUORUM_MIN_LOWER_BP
    if claims_passed < claims_total:
        return "CULLED_UNANCHORED_CLAIM", "AEO-R01", quorum_met
    if attempts == 0:
        return "UNVERIFIABLE_HOLD", "AEO-R04", quorum_met
    if not quorum_met:
        return "S2_CAPPED", "AEO-R04", quorum_met
    return "S4_VERIFIED", "PASS_ALL", quorum_met


def adjudicate(case_id, source, claims, stress_passes, stress_attempts):
    """Builds an unsigned source-anchoring payload. The stress counts are
    declared by the caller and the payload says so."""
    for name, v in (("stress_passes", stress_passes), ("stress_attempts", stress_attempts)):
        if isinstance(v, bool) or not isinstance(v, int):
            raise GateError("AEO-R02", "%s must be an integer" % name)
    if not (0 <= stress_passes <= stress_attempts <= 1000000):
        raise GateError("AEO-R02", "stress counts out of order")
    if not isinstance(case_id, str) or case_id == "":
        raise GateError("AEO-R02", "case_id is required")
    results, passed, sweep_hex = sweep_claims(source, claims)
    bp = wilson_bp(stress_passes, stress_attempts)
    disposition, rule, quorum_met = decide(len(claims), passed, stress_attempts, bp[0])
    return {
        "schema": SCHEMA,
        "kind": "source_anchoring",
        "case_id": case_id,
        "disposition": disposition,
        "rule_triggered": rule,
        "claims_total": len(claims),
        "claims_passed": passed,
        "claims": results,
        "stress_quorum": {
            "source": "declared_by_submitter",
            "attempts": stress_attempts,
            "passes": stress_passes,
            "wilson_ci95_bp": bp,
            "quorum_met": quorum_met,
        },
        "hashes": {
            "source_sha256": hashlib.sha256(source).hexdigest(),
            "sweep_fnv1a64": sweep_hex,
        },
    }


def sign_payload(payload, seed32, key_role):
    preimage = canonical_preimage(payload)
    return {
        "payload": payload,
        "signature": {
            "alg": "RFC8032-Ed25519",
            "key_role": key_role,
            "pubkey": ed25519_pubkey(seed32).hex(),
            "sig": ed25519_sign(seed32, preimage).hex(),
        },
    }


def verify_receipt(receipt, source=None, pubkey_hex=None):
    """Returns (ok, reason). `pubkey_hex` pins the expected signer."""
    try:
        payload = receipt["payload"]
        sig = receipt["signature"]
        pub = bytes.fromhex(sig["pubkey"])
        raw_sig = bytes.fromhex(sig["sig"])
        preimage = canonical_preimage(payload)
    except (KeyError, TypeError, ValueError):
        return False, "MALFORMED_RECEIPT"
    if payload.get("schema") != SCHEMA:
        return False, "UNKNOWN_SCHEMA"
    if pubkey_hex is not None and sig["pubkey"].lower() != pubkey_hex.lower():
        return False, "UNEXPECTED_SIGNER"
    if source is not None:
        declared = payload.get("hashes", {}).get("source_sha256")
        if declared != hashlib.sha256(source).hexdigest():
            return False, "SOURCE_HASH_MISMATCH"
    if not ed25519_verify(pub, preimage, raw_sig):
        return False, "INVALID_ED25519_SIGNATURE"
    return True, "RECEIPT_VERIFIED"


def replay_kernel_receipt(receipt, cohort_dir):
    """Recomputes a kernel_run receipt on this machine. Returns (ok, reason)."""
    sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
    import aeo_core as k
    import aeo_stress

    payload = receipt["payload"]
    if payload.get("kind") != "kernel_run":
        return False, "NOT_A_KERNEL_RUN"
    run = payload["run"]
    path = os.path.join(cohort_dir, run["cohort_id"] + ".csv")
    with open(path, "rb") as f:
        raw = f.read()
    if hashlib.sha256(raw).hexdigest() != run["cohort_sha256"]:
        return False, "COHORT_HASH_MISMATCH"
    rebuilt = aeo_stress.kernel_run_payload(payload["case_id"], run["config"], run["cohort_id"],
                                            raw, payload["claims_input"])
    if canonical_preimage(rebuilt) != canonical_preimage(payload):
        return False, "REPLAY_MISMATCH"
    return True, "REPLAY_MATCHED"


DEMO_CSV = (
    b"# assumption_target,cfe_24x7=0.9900,pue_marketing=1.05\n"
    b"metric,value,unit\n"
    b"annual_pue_mean,1.1842,ratio\n"
    b"cfe_24x7_match,0.8415,ratio\n"
)


def run_demo():
    seed = demo_seed()
    pue = {"metric": "pue", "needle": "annual_pue_mean,1.1842"}
    r1 = sign_payload(adjudicate("MT-DEMO-001-SHADOW", DEMO_CSV,
                                 [pue, {"metric": "cfe", "needle": "cfe_24x7=0.9900"}], 9, 10),
                      seed, "demo_public_seed")
    r2 = sign_payload(adjudicate("MT-DEMO-002-FLAKY", DEMO_CSV, [pue], 1, 6), seed, "demo_public_seed")
    r3 = sign_payload(adjudicate("MT-DEMO-003-VERIFIED", DEMO_CSV,
                                 [pue, {"metric": "cfe", "needle": "cfe_24x7_match,0.8415"}], 9, 10),
                      seed, "demo_public_seed")
    tampered = json.loads(json.dumps(r3))
    tampered["payload"]["stress_quorum"]["passes"] = 10
    return {
        "case_01_shadow_cull": {"disposition": r1["payload"]["disposition"],
                                "verified": list(verify_receipt(r1, DEMO_CSV))},
        "case_02_wilson_cap": {"disposition": r2["payload"]["disposition"],
                               "wilson_ci95_bp": r2["payload"]["stress_quorum"]["wilson_ci95_bp"],
                               "verified": list(verify_receipt(r2, DEMO_CSV))},
        "case_03_verified": {"disposition": r3["payload"]["disposition"],
                             "wilson_ci95_bp": r3["payload"]["stress_quorum"]["wilson_ci95_bp"],
                             "verified": list(verify_receipt(r3, DEMO_CSV))},
        "case_03_tamper_test": {"verified": list(verify_receipt(tampered, DEMO_CSV))},
        "sample_signed_receipt": r3,
    }


def _arg(argv, name, default=None):
    if name in argv:
        i = argv.index(name)
        if i + 1 < len(argv):
            return argv[i + 1]
    return default


def main(argv):
    if len(argv) >= 2 and argv[1] == "demo":
        print(json.dumps(run_demo(), indent=2, ensure_ascii=False))
        return 0
    if len(argv) >= 3 and argv[1] == "verify":
        with open(argv[2], "r", encoding="utf-8") as f:
            receipt = json.load(f)
        source = None
        if _arg(argv, "--source"):
            with open(_arg(argv, "--source"), "rb") as f:
                source = f.read()
        ok, reason = verify_receipt(receipt, source, _arg(argv, "--pubkey"))
        report = {"signature": reason}
        if ok and "--replay" in argv:
            ok, replay = replay_kernel_receipt(receipt, _arg(argv, "--cohort-dir", "data/cohorts"))
            report["replay"] = replay
        report["valid"] = ok
        print(json.dumps(report, indent=2))
        return 0 if ok else 1
    if len(argv) >= 2 and argv[1] == "adjudicate":
        with open(_arg(argv, "--source"), "rb") as f:
            source = f.read()
        with open(_arg(argv, "--claims"), "r", encoding="utf-8") as f:
            claims = json.load(f)
        with open(_arg(argv, "--seed-file"), "r", encoding="utf-8") as f:
            seed = bytes.fromhex(f.read().strip())
        if len(seed) != 32:
            raise GateError("AEO-R02", "seed file must hold 64 hex characters")
        payload = adjudicate(_arg(argv, "--case-id", "MT-LOCAL"), source, claims,
                             int(_arg(argv, "--stress-passes", "0")),
                             int(_arg(argv, "--stress-attempts", "0")))
        print(json.dumps(sign_payload(payload, seed, "self_attested"), indent=2, ensure_ascii=False))
        return 0
    print(__doc__)
    return 2


if __name__ == "__main__":
    sys.exit(main(sys.argv))
