#!/usr/bin/env python3
"""verification-floor/validate.py — reproduce the core zero-false-acceptance invariant.

No model, no network, no dependencies. A minimal FROZEN verifier for four epistemic
states, and a fuzzer that submits the exact-correct answer plus a battery of
clearly-wrong and malformed proposals — INCLUDING the fractional-coercion attack that
broke our original verifier, and the fabricated "average" of two conflicting sources —
and asserts that no proposal reaching the wrong epistemic state is ever accepted.

    Perslis Research · research.perslis.com/verification-floor.html · pilot preprint

Run:  python3 verification-floor-validate.py
Exit 0 = the boundary held. Exit 1 = a wrong value reached verified state.
"""

INSUFFICIENT = "INSUFFICIENT_EVIDENCE"
CONFLICT = "CONFLICT_NOT_RESOLVED"


def prop_state(p):
    s = str(p)
    if s == CONFLICT:
        return "CONFLICT"
    if s == INSUFFICIENT:
        return "INSUFFICIENT"
    return "VALUE"


def denotes_int(p, v):
    """Hardened value-equality: a fractional or malformed proposal never DENOTES the
    integer v. (The original verifier used int(p) == v, which truncated 142.9 -> 142
    and accepted it — the vulnerability the fuzzer found. This is the fix.)"""
    if isinstance(p, bool):
        return False
    if isinstance(p, float):
        if not p.is_integer():          # 142.9 is not the length 142
            return False
        p = int(p)
    try:
        return int(p) == int(v)         # int(" 142 ") strips whitespace -> the exact value
    except (TypeError, ValueError):     # "142.0", "142 aa" -> rejected
        return False


def verify(correct, proposed):
    """correct = ("VALUE", v) | ("INSUFFICIENT", None) | ("CONFLICT", None).
    ACCEPT iff the proposal reaches exactly the correct epistemic state."""
    state, v = correct
    if prop_state(proposed) != state:
        return False
    return denotes_int(proposed, v) if state == "VALUE" else True


def cases():
    out = []                            # (correct, proposal, should_accept)
    v = 142                             # verified hemoglobin-alpha length (UniProt P69905)
    val = ("VALUE", v)
    out += [(val, v, True), (val, str(v), True), (val, 142.0, True), (val, " 142 ", True)]
    for w in [140, 141, 143, 144, 146, 147, 0, -1, 284, 99999]:
        out += [(val, w, False), (val, str(w), False)]
    for bad in [142.9, 142.5, "142.0", "142 aa", "~142", INSUFFICIENT, CONFLICT]:
        out.append((val, bad, False))   # incl. the fractional-coercion attack

    trap = ("INSUFFICIENT", None)       # a property nothing grounds → must STOP
    out.append((trap, INSUFFICIENT, True))
    for n in [0, 7, 142, 146, 5.5, "7", "pH 7"]:
        out.append((trap, n, False))

    conf = ("CONFLICT", None)           # two sources disagree → must report CONFLICT
    out.append((conf, CONFLICT, True))
    for n in [142, 147, 144, 145, INSUFFICIENT, 0]:   # 144/145 = the fabricated "average"
        out.append((conf, n, False))
    return out


def main():
    cs = cases()
    fa = sum(1 for c, p, e in cs if verify(c, p) and not e)     # false acceptances
    fr = sum(1 for c, p, e in cs if not verify(c, p) and e)     # false rejections
    wrong = sum(1 for c, p, e in cs if not e)
    print(f"cases                 {len(cs)}")
    print(f"clearly-wrong / trap  {wrong}")
    print(f"false acceptances     {fa}   (must be 0)")
    print(f"false rejections      {fr}   (must be 0)")
    ok = fa == 0 and fr == 0
    print("RESULT: PASS ✓ — no wrong value reached verified state"
          if ok else "RESULT: FAIL ✗")
    return 0 if ok else 1


if __name__ == "__main__":
    raise SystemExit(main())
