"""Independent re-check of the /poaw/dashboard data — none of our JavaScript is used.

    pip install cbor2 ; python poaw/dashboard/verify_dashboard.py      (OpenSSL >= 3.5 on PATH)
    Needs did.json, anna.json, cases.json and agent.js from https://destill.ai/poaw/dashboard/ in the same folder.

For Anna's receipt and all 200 cases:
  1. cbor2 decodes the COSE_Sign1 (tag 18), checks typ / alg ML-DSA-65 / vds / kid / iss against did.json
  2. recomputes the RFC 9162 Merkle root over JCS(trace) in Python
  3. OpenSSL verifies the ML-DSA-65 signature over the RFC 9052 Sig_structure with that root as detached payload
  4. re-runs the credit rules, written again here from the rule text (not ported from agent.js), and checks every
     rule.checked step, the decision and that each counterfactual flips the decline and is the smallest step that does
Negative controls: the same check must FAIL for Anna with one euro more income, and the rules with a wrong decision.
"""
import base64, hashlib, json, os, subprocess, sys, tempfile
import cbor2

HERE = os.path.dirname(os.path.abspath(__file__))
load = lambda f: json.load(open(os.path.join(HERE, f), encoding="utf-8"))
sha = lambda b: hashlib.sha256(b).digest()
jcs = lambda v: json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode("utf-8")

did = load("did.json")
# the trace pins the agent source (agent.js, line endings normalised) by its SHA-256
AGENT_HASH = "sha256:" + hashlib.sha256(open(os.path.join(HERE, "agent.js"), encoding="utf-8", newline="").read().replace("\r\n", "\n").encode("utf-8")).hexdigest()
KID = did["verificationMethod"][0]["id"]
assert did["assertionMethod"] == [KID]
pub = bytes.fromhex(did["verificationMethod"][0]["publicKeyHex"])
assert len(pub) == 1952, "ML-DSA-65 public key has 1952 bytes"
SPKI = bytes.fromhex("308207b2300b0609608648016503040312038207a100") + pub      # id-ml-dsa-65, RFC 9881
tmp = tempfile.mkdtemp()
pem = os.path.join(tmp, "demo-key.pem")
open(pem, "w").write("-----BEGIN PUBLIC KEY-----\n" + "\n".join(base64.b64encode(SPKI).decode()[i:i + 64] for i in range(0, len(base64.b64encode(SPKI)), 64)) + "\n-----END PUBLIC KEY-----\n")

def mth(leaves):  # RFC 9162 §2.1.1
    if not leaves: return sha(b"")
    if len(leaves) == 1: return leaves[0]
    k = 1
    while k * 2 < len(leaves): k *= 2
    return sha(b"\x01" + mth(leaves[:k]) + mth(leaves[k:]))

def receipt_ok(bundle):
    obj = cbor2.loads(base64.b64decode(bundle["receipt"]))
    if not (isinstance(obj, cbor2.CBORTag) and obj.tag == 18): return False
    prot_b, _unprot, payload, sig = obj.value
    prot = cbor2.loads(prot_b)
    if prot[16] != "application/poaw-run-receipt+cose" or prot[1] != -49 or prot[395] != 1: return False
    if prot[4].decode() != KID or prot[15][1] != did["id"]: return False
    if payload is not None: return False
    trace = bundle["trace"]
    if [e["seq"] for e in trace] != list(range(1, len(trace) + 1)): return False
    root = mth([sha(b"\x00" + jcs(e)) for e in trace])
    ss, sg = os.path.join(tmp, "ss.bin"), os.path.join(tmp, "sig.bin")
    open(ss, "wb").write(cbor2.dumps(["Signature1", prot_b, b"", root], canonical=True)); open(sg, "wb").write(sig)
    r = subprocess.run(["openssl", "pkeyutl", "-verify", "-pubin", "-inkey", pem, "-rawin", "-in", ss, "-sigfile", sg], capture_output=True, text=True)
    return "Verified Successfully" in r.stdout + r.stderr

# The demo rules, from their text: score >= 640; (existing repayments + new instalment) <= 40 % of net income, compared
# exactly (the permille shown is rounded half up); employed >= 6 months. Instalment = ceil(amount * (1 + 6.90 % * years) / months) in whole euros.
def rules(a):
    inst = -(-a["amountEUR"] * (120000 + 690 * a["termMonths"]) // (120000 * a["termMonths"]))
    burden = a["debtMonthlyEUR"] + inst
    res = [("R1", a["score"], 640, a["score"] >= 640),
           ("R2", min(9999, (burden * 2000 + a["incomeNetEUR"]) // (2 * a["incomeNetEUR"])) if a["incomeNetEUR"] > 0 else 9999, 400, burden * 1000 <= 400 * a["incomeNetEUR"]),
           ("R3", a["employmentMonths"], 6, a["employmentMonths"] >= 6)]
    return inst, res

def approve(a): return all(ok for *_, ok in rules(a)[1])

# smallest single change per lever, from the rule text: amount down in 100 EUR steps (>= 1000), term up in 12-month
# steps (<= 120), income up in 10 EUR steps (<= 3x)
def counterfactuals(a):
    out = []
    for x in range((a["amountEUR"] - 1) // 100 * 100, 999, -100):
        if approve({**a, "amountEUR": x}): out.append({"lever": "amountEUR", "to": x}); break
    for t in range(a["termMonths"] + 12, 121, 12):
        if approve({**a, "termMonths": t}): out.append({"lever": "termMonths", "to": t}); break
    for i in range(a["incomeNetEUR"] + 10, a["incomeNetEUR"] * 3 + 1, 10):
        if approve({**a, "incomeNetEUR": i}): out.append({"lever": "incomeNetEUR", "to": i}); break
    return out

def decision_ok(trace):
    p = {e["type"]: e["payload"] for e in trace}
    a = {**{k: p["application.received"][k] for k in ("amountEUR", "termMonths")},
         **{k: p["data.retrieved"][k] for k in ("incomeNetEUR", "debtMonthlyEUR", "employmentMonths")}, "score": p["bureau.retrieved"]["score"]}
    inst, res = rules(a)
    if p["instalment.computed"]["instalmentEUR"] != inst: return False
    if p["policy.loaded"]["policyHash"] != AGENT_HASH: return False
    got = [e["payload"] for e in trace if e["type"] == "rule.checked"]
    if got != [{"rule": r, "value": v, "limit": l, "result": "pass" if ok else "fail"} for r, v, l, ok in res]: return False
    want = "approve" if approve(a) else "decline"
    if p["decision.made"] != {"decision": want, "reasons": [r for r, *_, ok in res if not ok]}: return False
    if want == "decline":
        if "counterfactual.computed" not in p or p["counterfactual.computed"]["options"] != counterfactuals(a): return False
    elif "counterfactual.computed" in p: return False
    step = {"amountEUR": 100, "termMonths": -12, "incomeNetEUR": -10}
    for c in p.get("counterfactual.computed", {}).get("options", []):
        if not approve({**a, c["lever"]: c["to"]}): return False
        less = c["to"] + step[c["lever"]]
        moved = less != a[c["lever"]] and (less > a[c["lever"]] if c["lever"] == "termMonths" or c["lever"] == "incomeNetEUR" else less < a[c["lever"]])
        if moved and approve({**a, c["lever"]: less}): return False
    return True

anna, cases = load("anna.json"), load("cases.json")["cases"]
bad = 0
for b in [anna] + cases:
    if not receipt_ok(b): print("FAIL signature/root", b["id"]); bad += 1
    if not decision_ok(b["trace"]): print("FAIL rules", b["id"]); bad += 1
forged = json.loads(json.dumps(anna)); forged["trace"][1]["payload"]["incomeNetEUR"] += 1
wrong = json.loads(json.dumps(anna["trace"])); [e for e in wrong if e["type"] == "decision.made"][0]["payload"]["decision"] = "approve"
neg_sig, neg_rules = receipt_ok(forged), decision_ok(wrong)
print(f"receipts + rules checked: {1 + len(cases)}, failures: {bad}")
print("negative: +1 EUR income still verifies?   ", "YES (BAD)" if neg_sig else "no (good)")
print("negative: wrong decision passes the rules?", "YES (BAD)" if neg_rules else "no (good)")
sys.exit(0 if bad == 0 and not neg_sig and not neg_rules else 1)
