#!/usr/bin/env python3
"""Independent exact arithmetic check of threshold.showcase.v1 (Python 3.10+).

No Threshold imports or third-party packages. Checks the published source/model
mapping, all reachable histories, every decision and the displayed policy. This
is bounded numerical verification, not issuer authentication, clinical validation
or a verifier for arbitrary Threshold certificates. Inputs are not executable.
"""
from fractions import Fraction
from functools import lru_cache
from hashlib import sha256
from itertools import product
from pathlib import Path
import json
import re
import sys


def require(ok, detail):
    if not ok:
        raise ValueError(detail)


def F(value):
    if type(value) is Fraction:
        return value
    require(type(value) in (str, int), "Expected an exact rational")
    if type(value) is str:
        require(len(value) <= 520 and re.fullmatch(r"-?[0-9]{1,256}(?:/[0-9]{1,256}|\.[0-9]{1,256})?", value), "Unsupported rational syntax or size")
    else:
        require(value.bit_length() <= 2048, "Oversized integer")
    return Fraction(value)


def canonical(x):
    return json.dumps(x, sort_keys=True, separators=(',', ':'), ensure_ascii=True)


def policy_key(p):
    return canonical({'kind': p['kind'], 'action': p['action'], 'branches':
                      [[o, json.loads(policy_key(c))] for o, c in sorted(p['branches'].items())]})


def verify(bundle):
    b = dict(bundle)
    claimed = b.pop('artifact_sha256')
    require(sha256(canonical(b).encode()).hexdigest() == claimed, 'Artifact content hash mismatch')
    require(b['schema'] == 'threshold.showcase.v1' and b['tier'] == 'synthetic'
            and b['clinical_validation'] == 'not_established', 'Unsupported scope')
    source, model, records = b['source'], b['model'], b['states']
    require(b['source_sha256'] == sha256(canonical(source).encode()).hexdigest(), 'Source hash mismatch')
    require(source['tier'] == 'synthetic' and source['schema'] == 'threshold.author.v1', 'Source scope')
    require(model['objective'] == source['assessment']['objective'] == 'minimax_regret', 'Objective mismatch')
    require(model['secondary_rule'] == 'minimax_expected_work_then_canonical_policy', 'Secondary rule')
    require(model['max_steps'] == source['budget']['steps'] == 2, 'Horizon')
    require(model['limits'] == source['budget']['resources'], 'Resources')
    require(F(model['tolerance']) == F(source['assessment']['tolerance']), 'Tolerance')
    require(b['case_id'] == source['id'], 'Case identity')
    require(set(model['states']) == set(source['states']) and len(source['states']) == 2, 'States')
    targets = list(source['targets'].values())
    require(len(targets) == 1 and len(targets[0]['positive_states']) == 1 and targets[0]['positive_states'][0] in source['states'], 'Target')
    positive = targets[0]['positive_states'][0]
    actions, decisions, models = model['actions'], model['decisions'], model['models']
    require(len(actions) == 2 and len(decisions) == 3 and len(models) == 2 and len(records) <= 64, 'Profile size')
    require(set(actions) == set(source['actions']) and set(decisions) == set(source['decisions']), 'Action domains')
    require(len({m['id'] for m in models}) == 2 and {m['id'] for m in models} == set(source['models']), 'Model domain')
    def rational(x):
        if isinstance(x, dict):
            if set(x) == {'ref'}:
                return rational(source['parameters'][x['ref']]['value'])
            if set(x) == {'complement'}:
                return 1 - rational(source['parameters'][x['complement']]['value'])
            raise ValueError('Unsupported source expression')
        return F(x[:-1]) / 100 if isinstance(x, str) and x.endswith('%') else F(x)
    for a, item in actions.items():
        original = source['actions'][a]
        require(1 <= len(item['outcomes']) <= 3, 'Observation budget')
        require(not original.get('repeatable') and not original.get('requires'), 'Action preconditions')
        require(F(item['cost']) == rational(original['cost']) == 0, 'Utility costs are outside this profile')
        require(item['resources'] == original['resources'], 'Action resources')
        require(item['label'] == original['label'] and item['outcomes'] == original['outcomes'], 'Action wording')
    for d, item in decisions.items():
        require(not source['decisions'][d].get('requires') and item['label'] == source['decisions'][d]['label'], 'Decision mapping')
    for m in models:
        original = source['models'][m['id']]
        require(set(m['prior']) == set(model['states']) and sum(map(F, m['prior'].values())) == 1, 'Prior normalisation')
        require(all(F(m['prior'][s]) == rational(original['prior'][s]) > 0 for s in model['states']), 'Prior mapping')
        for s in model['states']:
            require(set(m['utility'][s]) == set(decisions), 'Utility domain')
            for d in decisions:
                require(F(m['utility'][s][d]) == rational(original['utilities'][s][d]), 'Utility mapping')
            for a in actions:
                rows = original['transitions'][a][s]
                require(all(e['to'] == s for e in rows), 'State transitions are outside this profile')
                actual = m['likelihood'][a][s]
                expected = {e['outcome']: rational(e['p']) for e in rows}
                require(set(actual) == set(actions[a]['outcomes']) == set(expected), 'Observation domain')
                require({o: F(p) for o, p in actual.items()} == expected and sum(expected.values()) == 1
                        and all(p > 0 for p in expected.values()), 'Observation mapping')
    tolerance = F(model['tolerance'])
    require(tolerance >= 0, 'Negative tolerance')
    variants = b['presentation']['variants']
    require(b['presentation']['clinical_validation'] == 'not_established'
            and 1 <= len(variants) <= 8 and len({v['id'] for v in variants}) == len(variants), 'Presentation scope')
    for v in variants:
        require(set(v['outcomes']) == set(actions) and all(v['outcomes'][a] in actions[a]['outcomes'] for a in actions), 'Variant coverage')

    def posterior(m, history):
        mass = {s: F(p) for s, p in m['prior'].items()}
        for a, o in history:
            mass = {s: p * F(m['likelihood'][a][s][o]) for s, p in mass.items()}
        total = sum(mass.values())
        require(total > 0, 'Impossible history')
        return {s: p / total for s, p in mass.items()}

    def available(history):
        if len(history) >= model['max_steps']:
            return []
        used = {a for a, _ in history}
        return [a for a in actions if a not in used and all(
            sum(actions[h]['resources'][r] for h, _ in history) + actions[a]['resources'][r] <= cap
            for r, cap in model['limits'].items())]

    # Enumeration is independent of the producer: recursively combine exact
    # conditional expected values and resource use at each observable branch.
    @lru_cache(None)
    def enumerate_at(history):
        beliefs = [posterior(m, history) for m in models]
        candidates = []
        for d in decisions:
            values = tuple(sum(p * F(m['utility'][s][d]) for s, p in belief.items())
                           for m, belief in zip(models, beliefs))
            candidates.append(({'kind': 'stop', 'action': d, 'branches': {}}, values, (F(0),) * len(models)))
        for a in available(history):
            outcomes = sorted(actions[a]['outcomes'])
            pools = [enumerate_at(history + ((a, o),)) for o in outcomes]
            probabilities = [[sum(p * F(m['likelihood'][a][s][o]) for s, p in belief.items())
                              for o in outcomes] for m, belief in zip(models, beliefs)]
            for children in product(*pools):
                values = tuple(sum(probabilities[i][j] * child[1][i] for j, child in enumerate(children)) for i in range(len(models)))
                work = tuple(F(actions[a]['resources']['work']) + sum(probabilities[i][j] * child[2][i] for j, child in enumerate(children)) for i in range(len(models)))
                candidates.append(({'kind': 'ask', 'action': a, 'branches': {o: c[0] for o, c in zip(outcomes, children)}}, values, work))
        require(len(candidates) <= 10000, 'Policy budget exceeded')
        return candidates

    pending, visited = [()], set()
    while pending:
        history = pending.pop(0)
        key = '|'.join(f'{a}:{o}' for a, o in history) or 'initial'
        visited.add(key)
        r = records[key]
        require(r['verification'] == 'verified', f'{key}: producer did not verify')
        require(r['history'] == [{'action': a, 'outcome': o} for a, o in history], f'{key}: history')
        post = {m['id']: posterior(m, history)[positive] for m in models}
        require({m: F(p) for m, p in r['posterior'].items()} == post, f'{key}: posterior')
        require(list(map(F, r['range'])) == [min(post.values()), max(post.values())], f'{key}: range')
        next_states = {a: {o: '|'.join(f'{h}:{v}' for h, v in history + ((a, o),)) for o in sorted(actions[a]['outcomes'])} for a in available(history)}
        require(r['next'] == next_states, f'{key}: reachable transitions')
        for a in available(history):
            pending.extend(history + ((a, o),) for o in sorted(actions[a]['outcomes']))
        candidates = enumerate_at(history)
        oracle = tuple(max(c[1][i] for c in candidates) for i in range(len(models)))
        def regret(c):
            return max(o - v for o, v in zip(oracle, c[1]))
        optimum = min(map(regret, candidates))
        tied = [c for c in candidates if regret(c) == optimum]
        reference = min(tied, key=lambda c: (max(c[2]), policy_key(c[0])))
        require(r['reference'] == reference[0] and list(map(F, r['reference_values'])) == list(reference[1])
                and list(map(F, r['reference_work'])) == list(reference[2]), f'{key}: displayed reference')
        require(r['candidate_policies'] == len(candidates) and r['primary_optimal_policies'] == len(tied), f'{key}: policy counts')
        continuations = [c for c in candidates if c[0]['kind'] == 'ask']
        require(set(r['decisions']) == set(decisions), f'{key}: decision coverage')
        for d, record in r['decisions'].items():
            learner = next(c for c in candidates if c[0]['kind'] == 'stop' and c[0]['action'] == d)
            gain = lambda c: min(x - y for x, y in zip(c[1], learner[1]))
            advantage = max(map(gain, candidates))
            alternative = min((c for c in candidates if gain(c) == advantage), key=lambda c: policy_key(c[0]))
            gap = max(max(c[1][i] for c in continuations) - learner[1][i] for i in range(len(models))) if continuations else None
            classification = ('supported_criticism' if advantage > tolerance else 'robustly_supported' if regret(learner) <= tolerance
                              else 'reasonable_alternative' if regret(learner) - optimum <= tolerance else 'assumption_dependent')
            require(record['classification'] == classification, f'{key}/{d}: classification')
            require(F(record['maximum_regret']) == regret(learner) and list(map(F, record['learner_values'])) == list(learner[1]), f'{key}/{d}: values')
            require(record['stopping_established'] == (gap is None or gap <= tolerance), f'{key}/{d}: stopping claim')
            require((F(record['stopping_gap']) if record['stopping_gap'] is not None else None) == gap, f'{key}/{d}: stopping gap')
            require(record['guaranteed_advantage'] is None if classification != 'supported_criticism' else F(record['guaranteed_advantage']) == advantage, f'{key}/{d}: guaranteed gain')
            expected_alternative = alternative[0] if classification == 'supported_criticism' else None
            require(record['alternative'] == expected_alternative, f'{key}/{d}: alternative')
            reasons = {'supported_criticism': 'common_executable_alternative', 'robustly_supported': 'within_tolerance_in_every_model',
                       'reasonable_alternative': 'declared_ambiguity_criterion', 'assumption_dependent': 'no_uniformly_better_policy_established'}
            require(record['reason'] == reasons[classification], f'{key}/{d}: reason')
    require(visited == set(records), 'Extra or missing history records')
    # The registry is derived from this checked model; ensure every numerical
    # entry is represented exactly once, including complements and budgets.
    expected = {}
    for m in models:
        for s, p in m['prior'].items(): expected[f"{m['id']}.prior.{s}"] = F(p)
        for a, rows in m['likelihood'].items():
            for s, outcomes in rows.items():
                for o, p in outcomes.items(): expected[f"{m['id']}.{a}.{s}.{o}"] = F(p)
        for s, row in m['utility'].items():
            for d, u in row.items(): expected[f"{m['id']}.utility.{s}.{d}"] = F(u)
    for a, item in actions.items():
        expected[f'{a}.cost'] = F(item['cost'])
        for k, v in item['resources'].items(): expected[f'{a}.resources.{k}'] = F(v)
    for k, v in model['limits'].items(): expected[f'budget.{k}'] = F(v)
    expected.update({'budget.steps': F(model['max_steps']), 'assessment.tolerance': tolerance})
    require(len(b['registry']) == len(expected) and {e['id']: F(e['value']) for e in b['registry']} == expected, 'Registry coverage')
    require(all(e['status'] == 'synthetic' and e['review'] == 'not_clinically_reviewed' for e in b['registry']), 'Registry status')
    return {'status': 'verified', 'histories': len(visited), 'decisions': sum(len(r['decisions']) for r in records.values()),
            'clinical_validation': 'not_established', 'artifact_sha256': claimed}


def load(path):
    require(path.stat().st_size <= 2_000_000, 'File exceeds public profile size limit')
    def unique(pairs):
        out = {}
        for key, value in pairs:
            require(key not in out, 'Duplicate JSON key')
            out[key] = value
        return out
    return json.loads(path.read_text(encoding='utf-8'), object_pairs_hook=unique)


if __name__ == '__main__':
    try:
        require(len(sys.argv) == 2, 'Usage: python3 verify_showcase.py showcase.json')
        print(json.dumps(verify(load(Path(sys.argv[1]))), indent=2))
    except (ValueError, KeyError, TypeError, IndexError, ZeroDivisionError, OSError, RecursionError) as error:
        print(f'NOT VERIFIED: {error}', file=sys.stderr)
        sys.exit(1)
