"""Independent finite-model checks for the closed research loop experiment."""

from itertools import combinations, product


def _evaluate(formula, model):
    operation = formula['op']
    if operation == 'ref':
        return model[formula['atom']]
    arguments = formula['args']
    if operation == 'not':
        return not _evaluate(arguments[0], model)
    if operation == 'all':
        return all(_evaluate(argument, model) for argument in arguments)
    if operation == 'implies':
        return not _evaluate(arguments[0], model) or _evaluate(arguments[1], model)
    raise AssertionError(f'Unexpected operation {operation!r}')


def _symbols(formula):
    if formula['op'] == 'ref':
        return {formula['atom']}
    return set().union(*map(_symbols, formula['args']))


def _models(symbols, rules):
    for values in product((False, True), repeat=len(symbols)):
        model = dict(zip(symbols, values))
        if all(_evaluate(rule, model) for rule in rules):
            yield model


def _status(models, anchor):
    values = {model[anchor] for model in models}
    assert values, f'No model for {anchor}'
    if len(values) == 1:
        return 'KNOWN', values.pop()
    return 'UNKNOWN', None


def _sufficient_sets(models, target, inventory):
    sufficient = []
    for size in range(1, len(inventory) + 1):
        for group in combinations(inventory, size):
            group = frozenset(group)
            if any(existing < group for existing in sufficient):
                continue
            possible_models = [model for model in models if all(model[anchor] for anchor in group)]
            if possible_models and all(model[target] for model in possible_models):
                sufficient.append(group)
    return set(sufficient)


def audit(case, trace):
    """Verify logical and observable outcomes without importing the runtime."""
    anchors = case['anchors']
    rules = case['rules']
    inventory = set(case['inventory'])
    symbols = sorted(set(anchors.values()) | inventory | set().union(*map(_symbols, rules)))
    worlds = list(_models(symbols, rules))
    rounds = trace['rounds']
    assert len(rounds) > 2, 'The loop must proceed across multiple rounds'
    assert rounds[0]['evidence'] is None, 'The initial proof round must precede acquisition'
    assert rounds[0]['decision']['results'][anchors['n']]['publication'], 'The initial conclusion must be published'
    assert rounds[-1]['evidence'] is None and rounds[-1]['decision']['query'] is None, 'The loop must finish without a selected acquisition'

    observed = []
    first_questions = {}
    statuses = 0
    checked_gaps = 0
    publications = {}
    for index, entry in enumerate(rounds):
        decision = entry['decision']
        facts = decision['facts']
        model_at_round = [model for model in worlds if all(_evaluate(fact, model) for fact in facts.values())]
        assert all(_symbols(fact) == {anchor} for anchor, fact in facts.items())
        assert model_at_round, f'Inconsistent fact context in round {index}'
        for anchor, result in decision['results'].items():
            assert anchor not in facts, f'Already recalled question {anchor} was offered again'
            first_questions.setdefault(anchor, index)
            status, value = _status(model_at_round, anchor)
            response = result['response']
            assert (response['epistemic'], response['known_value']) == (status, value)
            statuses += 1
            if status == 'UNKNOWN':
                assert not result['publication'], f'UNKNOWN was published for {anchor}'
                missing = _sufficient_sets(model_at_round, anchor, sorted(inventory - facts.keys()))
                assert set(map(frozenset, decision['gaps'][anchor])) == missing, f'Incorrect sufficient sets for {anchor}'
                checked_gaps += 1
            if result['publication']:
                assert status == 'KNOWN' and value is True
                assert anchor not in publications, f'Duplicate publication for {anchor}'
                selected = result['selected']
                assert set(selected) <= facts.keys()
                models_of_support = [model for model in worlds if all(_evaluate(facts[a], model) for a in selected)]
                assert _status(models_of_support, anchor) == ('KNOWN', True), f'Published support fails for {anchor}'
                publications[anchor] = index

        evidence = entry['evidence']
        if evidence is None:
            assert decision['query'] is None, f'Unexecuted query in round {index}'
            continue
        anchor = evidence['anchor']
        assert anchor == decision['query'] and anchor in inventory and anchor not in facts
        assert anchor in {missing for groups in decision['gaps'].values() for group in groups for missing in group}
        assert anchor not in {prior['anchor'] for prior in observed}, f'Repeated source request for {anchor}'
        delta = evidence['delta']
        assert len(delta) <= 1 and all(_symbols(fact) == {anchor} for fact in delta)
        if index + 1 < len(rounds):
            next_facts = rounds[index + 1]['decision']['facts']
            if delta:
                assert next_facts.get(anchor) == delta[0], f'Signed literal missing in the following epoch for {anchor}'
            else:
                assert anchor not in next_facts, f'No-hit became evidence for {anchor}'
        observed.append(evidence | {'round': index})

    assert observed and observed[0]['anchor'] == anchors['m']
    source_delta = observed[0]['delta']
    assert source_delta in ([], [{'op': 'ref', 'atom': anchors['m']}],
                           [{'op': 'not', 'args': [{'op': 'ref', 'atom': anchors['m']}]}])
    outcome = 'no-hit' if not source_delta else 'positive' if source_delta[0]['op'] == 'ref' else 'negative'
    requested = [row['anchor'] for row in observed]
    outcome_round = observed[0]['round'] + 1
    after_first_result = rounds[outcome_round]['decision']
    m = anchors['m']
    direct_support = {frozenset(group) for group in after_first_result['gaps'].get(anchors['f'], [])}
    if outcome == 'no-hit':
        assert frozenset({m}) in direct_support, 'No-hit must retain the direct proof path as a logical possibility'
    elif outcome == 'negative':
        assert all(m not in group for group in direct_support), 'A negative literal must eliminate its positive proof path'
        assert first_questions[anchors['z']] >= outcome_round
    assert (anchors['z'] in first_questions) == (outcome == 'negative')
    assert all(row['delta'] == [{'op': 'ref', 'atom': row['anchor']}] for row in observed[1:])
    if outcome == 'positive':
        assert requested == [anchors['m'], anchors['k']]
        required_publications = {'n', 'f', 'l', 't'}
    else:
        prefix = [anchors['m'], anchors['r']] if outcome == 'negative' else [anchors['m']]
        assert requested[:-3] == prefix and requested[-1] == anchors['k']
        assert set(requested[-3:-1]) == {anchors['v'], anchors['w']}
        required_publications = {'n', 'f', 't', 'z'} if outcome == 'negative' else {'n', 'f', 't'}
    assert set(publications) == {anchors[name] for name in required_publications}
    assert first_questions[anchors['t']] > publications[anchors['f']], 'The next question must use the new conclusion'
    return {'first_outcome': outcome, 'executed_requests': requested, 'checked_statuses': statuses,
            'checked_gap_sets': checked_gaps, 'publications': publications, 'first_questions': first_questions}
