"""Threshold public verifier for rich-case bundles (standalone; needs only the Python standard library).

Recomputes everything a bundle claims from the case source it carries, in exact arithmetic, and compares every
rounded number, reference choice and verdict. Usage: python3 verify_rich.py BUNDLE.json [BUNDLE.json ...]

This is a copy of threshold.rich_check from arcifact-core, kept byte-for-byte in its logic so that anyone can re-run
the checks without the rest of the engine.

Independent checker for rich cases.

Deliberately shares no code with threshold.rich. It parses the draft itself, builds the models itself, enumerates every
affordable set of findings bottom-up (largest sets first) instead of recursing top-down, computes each state's joint
weights directly from the prior and every likelihood instead of incrementally, and then checks:

1. every information state and every option value of a producer solution, exactly;
2. the local optimality equations at every state (the "working", line by line):
       V(I) = max_x Q(I, x)
       Q(I, d) = sum_c P(c | I) U(c, d)
       Q(I, a) = sum_o P(o | I) V(I + (a, o)) - burden(a) - minute_cost * minutes(a)
3. an exported bundle: every rounded number against the exact value, and every verdict, 'better' option, 'could
   change the call' flag and 'enough' flag against this module's own derivation.
"""
from __future__ import annotations

import hashlib
import itertools
import json
from fractions import Fraction

REQUESTED = "requested"


class CheckFailure(AssertionError):
    pass


def _q(value):
    if isinstance(value, bool) or isinstance(value, float):
        raise CheckFailure("binary float in an exact field")
    if isinstance(value, int):
        return Fraction(value)
    text = str(value).strip()
    return Fraction(text[:-1]) / 100 if text.endswith("%") else Fraction(text)


def _round(value: Fraction, places: int) -> str:
    scale = 10 ** places
    n = abs(value) * scale
    whole, rem = divmod(n.numerator, n.denominator)
    if 2 * rem >= n.denominator:
        whole += 1
    sign = "-" if value < 0 and whole else ""
    return f"{sign}{whole // scale}.{whole % scale:0{places}d}"


class Independent:
    def __init__(self, draft: dict):
        self.causes = list(draft["causes"])
        self.actions = list(draft["actions"])
        self.decisions = list(draft["decisions"])
        cons = draft["consultation"]
        self.budget, self.minute_cost, self.tol = cons["minutes"], _q(cons["minute_cost"]), _q(cons["materiality"])
        self.minutes = {a: draft["actions"][a]["minutes"] for a in self.actions}
        self.delayed = {a: bool(draft["actions"][a].get("delayed", False)) for a in self.actions}
        self.positive = list(draft["target"]["positive"])
        qs = draft["quantities"]
        banded = [n for n in qs if "band" in qs[n]]
        if "models" in draft:
            specs = [(s["id"], s["choose"]) for s in draft["models"]]
        else:
            specs = []
            for sides in itertools.product(("low", "high"), repeat=len(banded)):
                specs.append(("__".join(n + "_" + s for n, s in zip(banded, sides)) or "point", dict(zip(banded, sides))))
        self.models = [mid for mid, _ in specs]
        self.tables = {}
        for mid, choose in specs:
            num = {}
            for n, q in qs.items():
                num[n] = _q(q["band"][1 if choose.get(n) == "high" else 0]) if "band" in q else _q(q["value"])
            look = lambda r: num[r] if isinstance(r, str) and r in num else _q(r)
            prior = {c: look(draft["prior"][c]) for c in self.causes if draft["prior"][c] != "remainder"}
            left = [c for c in self.causes if draft["prior"][c] == "remainder"][0]
            prior[left] = 1 - sum(prior.values())
            lik, burden = {}, {}
            for a in self.actions:
                spec = draft["actions"][a]
                burden[a] = look(spec.get("burden", "0"))
                if self.delayed[a]:
                    lik[a] = {REQUESTED: {c: Fraction(1) for c in self.causes}}
                    continue
                table = {o: {c: look(v["p"][c]) for c in self.causes} for o, v in spec["outcomes"].items() if v["p"] != "remainder"}
                for o, v in spec["outcomes"].items():
                    if v["p"] == "remainder":
                        table[o] = {c: 1 - sum(table[x][c] for x in table) for c in self.causes}
                lik[a] = table
            util = {c: {d: look(draft["utilities"][c][d]) for d in self.decisions} for c in self.causes}
            self.tables[mid] = (prior, lik, util, burden)
        self.V, self.Q = {m: {} for m in self.models}, {m: {} for m in self.models}
        self._solve()

    def outs(self, a):
        return [REQUESTED] if self.delayed[a] else list(self.tables[self.models[0]][1][a])

    def joint(self, m, obs):
        prior, lik, _, _ = self.tables[m]
        return {c: prior[c] * _prod(lik[a][o][c] for a, o in obs) for c in self.causes}

    def key(self, obs):
        order = {a: i for i, a in enumerate(self.actions)}
        return "|".join(f"{a}={o}" for a, o in sorted(obs, key=lambda x: order[x[0]])) or "start"

    def _all_states(self):
        subsets = [s for r in range(len(self.actions), -1, -1) for s in itertools.combinations(self.actions, r)
                   if sum(self.minutes[a] for a in s) <= self.budget]
        for subset in subsets:                      # largest sets first: successors are always done before predecessors
            for combo in itertools.product(*(self.outs(a) for a in subset)):
                yield subset, frozenset(zip(subset, combo))

    def _options(self, subset):
        left = self.budget - sum(self.minutes[a] for a in subset)
        return [a for a in self.actions if a not in subset and self.minutes[a] <= left]

    def _solve(self):
        states = list(self._all_states())
        self.policy, self.mix_q, self.mix_v = {}, {}, {}
        for subset, obs in states:                  # the equal-weight mixture, bottom-up
            mass = {m: sum(self.joint(m, obs).values()) for m in self.models}
            total = sum(mass.values())
            q = {}
            for d in self.decisions:
                q[d] = sum(self.joint(m, obs)[c] * self.tables[m][2][c][d] for m in self.models for c in self.causes) / total
            for a in self._options(subset):
                expect = Fraction(0)
                for o in self.outs(a):
                    nxt = obs | {(a, o)}
                    expect += sum(sum(self.joint(m, nxt).values()) for m in self.models) / total * self.mix_v[nxt]
                q[a] = expect - sum(mass[m] / total * self.tables[m][3][a] for m in self.models) - self.minute_cost * self.minutes[a]
            top = max(q.values())
            self.mix_q[obs], self.mix_v[obs] = q, top
            self.policy[obs] = next(x for x in self.decisions + self._options(subset) if q[x] == top)
        for m in self.models:                       # each model evaluated under the one reference policy, bottom-up
            _, _, util, burden = self.tables[m]
            for subset, obs in states:
                j = self.joint(m, obs)
                z = sum(j.values())
                q = {d: sum(j[c] * util[c][d] for c in self.causes) / z for d in self.decisions}
                for a in self._options(subset):
                    total = sum(sum(self.joint(m, obs | {(a, o)}).values()) / z * self.V[m][obs | {(a, o)}] for o in self.outs(a))
                    q[a] = total - burden[a] - self.minute_cost * self.minutes[a]
                self.Q[m][obs], self.V[m][obs] = q, q[self.policy[obs]]

    def verdict(self, obs, x):
        gap = {m: max(self.Q[m][obs].values()) - self.Q[m][obs][x] for m in self.models}
        near = [gap[m] <= self.tol for m in self.models]
        if all(near):
            return "sound", None
        if any(near):
            return "depends", None
        best, lead_best = None, None
        for y in self.decisions + self.actions:
            if y == x or y not in self.Q[self.models[0]][obs]:
                continue
            lead = min(self.Q[m][obs][y] - self.Q[m][obs][x] for m in self.models)
            if lead > self.tol and (lead_best is None or lead > lead_best):
                best, lead_best = y, lead
        return ("criticised", best) if best else ("also_sound", None)

    def best_calls(self, m, obs):
        top = max(self.Q[m][obs][d] for d in self.decisions)
        return {d for d in self.decisions if self.Q[m][obs][d] == top}

    def could_change(self, obs, a):
        if self.delayed[a]:
            return None
        return any(not (self.best_calls(m, obs) & self.best_calls(m, obs | {(a, o)})) for m in self.models for o in self.outs(a))

    def settled(self, obs):
        return all(max(self.Q[m][obs][d] for d in self.decisions) >= max(self.Q[m][obs].values()) - self.tol for m in self.models)

    def check_local_equations(self):
        """The working, line by line, for the mixture and for every model under the reference policy."""
        for obs, q in self.mix_q.items():
            if self.mix_v[obs] != max(q.values()) or q[self.policy[obs]] != self.mix_v[obs]:
                raise CheckFailure(f"mixture {self.key(obs)}: the reference is not the best option")
        for m in self.models:
            _, _, util, burden = self.tables[m]
            for obs, q in self.Q[m].items():
                if self.V[m][obs] != q[self.policy[obs]]:
                    raise CheckFailure(f"{m} {self.key(obs)}: value is not the reference option's value")
                j = self.joint(m, obs)
                z = sum(j.values())
                for x, value in q.items():
                    if x in self.decisions:
                        expect = sum(j[c] / z * util[c][x] for c in self.causes)
                    else:
                        expect = sum(sum(self.joint(m, obs | {(x, o)}).values()) / z * self.V[m][obs | {(x, o)}] for o in self.outs(x))
                        expect -= burden[x] + self.minute_cost * self.minutes[x]
                    if value != expect:
                        raise CheckFailure(f"{m} {self.key(obs)} {x}: option value does not follow from its successors")
        return len(self.policy)


def _prod(values):
    out = Fraction(1)
    for v in values:
        out *= v
    return out


def check_solution(draft: dict, solution) -> dict:
    """Compare a producer solution (any object with states(m), value(m, obs) and q(m, obs)) with this derivation."""
    ind = Independent(draft)
    checked = ind.check_local_equations()
    if set(solution.states()) != set(ind.policy):
        raise CheckFailure(f"the producer solved {len(solution.states())} states, the checker derives {len(ind.policy)}")
    for obs in ind.policy:
        if solution.reference(obs) != ind.policy[obs] or solution.mixture_q(obs) != ind.mix_q[obs]:
            raise CheckFailure(f"{ind.key(obs)}: reference policy differs")
        for m in ind.models:
            if solution.value(m, obs) != ind.V[m][obs] or solution.q(m, obs) != ind.Q[m][obs]:
                raise CheckFailure(f"{m} {ind.key(obs)}: values differ")
    return {"status": "verified", "models": ind.models, "states_checked": checked}


def _canonical(value) -> str:
    return json.dumps(value, sort_keys=True, separators=(",", ":"), ensure_ascii=True)


def check_bundle(bundle: dict) -> dict:
    """Recompute everything a bundle claims from its own source and compare: digests, rounded values, verdicts."""
    body = {k: v for k, v in bundle.items() if k != "artifact_sha256"}
    if hashlib.sha256(_canonical(body).encode()).hexdigest() != bundle["artifact_sha256"]:
        raise CheckFailure("artifact digest")
    draft = bundle["source"]
    if hashlib.sha256(_canonical(draft).encode()).hexdigest() != bundle["source_sha256"]:
        raise CheckFailure("source digest")
    ind = Independent(draft)
    places = bundle["precision"]
    count = 0
    for vid, v in bundle["variants"].items():
        inst = v["instance"]
        shown = {a: (REQUESTED if ind.delayed[a] else inst[a]) for a in ind.actions}
        expected_keys = set()
        for r in range(len(ind.actions) + 1):
            for subset in itertools.combinations(ind.actions, r):
                if sum(ind.minutes[a] for a in subset) <= ind.budget:
                    expected_keys.add(frozenset((a, shown[a]) for a in subset))
        if v.get("truth") is not None and v["truth"] not in ind.causes:
            raise CheckFailure(f"{vid}: the story's cause is not one of the causes")
        if {ind.key(o) for o in expected_keys} != set(v["states"]):
            raise CheckFailure(f"{vid}: the exported states are not exactly the reachable states")
        for obs in expected_keys:
            rec = v["states"][ind.key(obs)]
            where = f"{vid} {ind.key(obs)}"
            if rec["minutes_used"] != sum(ind.minutes[a] for a, _ in obs) or rec["settled"] != ind.settled(obs):
                raise CheckFailure(f"{where}: minutes or enough flag")
            for m in ind.models:
                j = ind.joint(m, obs)
                z = sum(j.values())
                if rec["value"][m] != _round(ind.V[m][obs], places):
                    raise CheckFailure(f"{where}: value in {m}")
                if any(rec["posterior"][m][c] != _round(j[c] / z, places) for c in ind.causes):
                    raise CheckFailure(f"{where}: posterior in {m}")
                if rec["target"][m] != _round(sum(j[c] for c in ind.positive) / z, places):
                    raise CheckFailure(f"{where}: target in {m}")
                if sorted(rec["best"][m]) != sorted(x for x, q in ind.Q[m][obs].items() if q == max(ind.Q[m][obs].values())):
                    raise CheckFailure(f"{where}: best options in {m}")
            if rec["reference"] != ind.policy[obs]:
                raise CheckFailure(f"{where}: reference option")
            if set(rec["options"]) != set(ind.Q[ind.models[0]][obs]):
                raise CheckFailure(f"{where}: option set")
            for x, o in rec["options"].items():
                if any(o["q"][m] != _round(ind.Q[m][obs][x], places) for m in ind.models):
                    raise CheckFailure(f"{where} {x}: option value")
                verdict, better = ind.verdict(obs, x)
                if (o["verdict"], o["better"]) != (verdict, better):
                    raise CheckFailure(f"{where} {x}: verdict {o['verdict']}/{o['better']} but the checker derives {verdict}/{better}")
                if o["could_change"] != (ind.could_change(obs, x) if x in ind.actions else None):
                    raise CheckFailure(f"{where} {x}: could-change flag")
                count += 1
    return {"status": "verified", "variants": list(bundle["variants"]), "options_checked": count}

def main(argv=None) -> int:
    import sys
    paths = (argv if argv is not None else sys.argv[1:])
    if not paths:
        print("usage: verify_rich.py BUNDLE.json [BUNDLE.json ...]", file=sys.stderr)
        return 2
    failed = 0
    for path in paths:
        try:
            with open(path, encoding="utf-8") as handle:
                report = check_bundle(json.load(handle))
            print(json.dumps({"bundle": path, **report}))
        except (CheckFailure, KeyError, ValueError, TypeError) as error:
            failed += 1
            print(json.dumps({"bundle": path, "status": "failed", "detail": str(error)}), file=sys.stderr)
    return 1 if failed else 0


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