"""Replay the Saltmere handover support checks with the pinned Semantica engine.

Install requirements.txt (Python 3.12) and run `python saltmere-filter.py --check`.
Use `--write` to regenerate filter-results.json. With `--check-record` only the
small independent support-set check runs; that mode needs only Python 3.
"""
import argparse
from copy import deepcopy
from importlib.metadata import version
import json
from pathlib import Path

ROOT = Path(__file__).resolve().parent
CASE_FILE = ROOT / 'support-map.json'
RESULT_FILE = ROOT / 'filter-results.json'
ENGINE_VERSION = '0.7.0'
ENGINE_COMMIT = 'ca6c9f1918ad05e2bbaa4922fb32f34e2a508bb9'
SESSION = 'foray-236-saltmere-handover'


def conditions(case):
    intact = {key: claim['supports'] for key, claim in case['claims'].items()}
    omitted = deepcopy(intact)
    edge = case['omitted_edge']
    omitted[edge['claim']].remove(edge['support'])
    repaired = deepcopy(omitted)
    repaired[edge['claim']].append(edge['support'])
    return {'intact': intact, 'omitted': omitted, 'repaired': repaired}


def events(case):
    return {'original': None, **{name: rev['withdraw'] for name, rev in case['revisions'].items()}}


def selection(claim_ids, retained):
    return {'retained': sorted(retained), 'review': sorted(set(claim_ids) - set(retained))}


def independent_result(case):
    result = {}
    for name, links in conditions(case).items():
        result[name] = {}
        for event, withdrawn in events(case).items():
            retained = [claim for claim, required in links.items() if withdrawn not in required]
            result[name][event] = selection(links, retained)
    return result


def native_result(case):
    from semantica.context import RetrievedContext, TruthMaintenanceContextFilter
    from semantica.reasoning import FactSupport, Rule, TruthMaintenanceSession

    if version('semantica') != ENGINE_VERSION:
        raise ValueError('Install the reviewed version from requirements.txt')
    result = {}
    for name, links in conditions(case).items():
        rules = [Rule('rule-' + claim, case['claims'][claim]['label'],
                      ['Current(' + source + ')' for source in required], 'Supported(' + claim + ')')
                 for claim, required in links.items()]
        baseline = TruthMaintenanceSession(rules=rules)
        baseline.apply(assertions=[FactSupport(source, 'Current(' + source + ')') for source in case['sources']])
        checkpoint = json.dumps(baseline.to_checkpoint())
        candidates = [RetrievedContext(content=c['label'], score=1.0, source=key, metadata={
            'truth_maintenance': {'schema_version': 1, 'session_id': SESSION,
                                  'required_facts': ['Supported(' + key + ')'], 'required_support_ids': []}
        }) for key, c in case['claims'].items()]
        result[name] = {}
        for event, withdrawn in events(case).items():
            # Each revision starts with the unmodified baseline, including the name-only control.
            session = TruthMaintenanceSession.from_checkpoint(json.loads(checkpoint))
            if withdrawn:
                session.apply(retractions=[withdrawn], assertions=[FactSupport(event, 'Revised(' + withdrawn + ')')])
            gate = TruthMaintenanceContextFilter(session, session_id=SESSION)
            kept = gate.filter_contexts(candidates, snapshot=gate.snapshot())
            result[name][event] = selection(links, [item.source for item in kept])
    return result


def record(result):
    return {'engine': 'Semantica', 'version': ENGINE_VERSION, 'source_commit': ENGINE_COMMIT,
            'decision': 'Review means the old grouped claim lost required support. The filter does not determine capacity or book a trailer.',
            'selections': result}


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    modes = parser.add_mutually_exclusive_group(required=True)
    for mode in ('--check', '--check-record', '--write'):
        modes.add_argument(mode, action='store_true')
    args = parser.parse_args()
    case = json.loads(CASE_FILE.read_text())
    expected = record(independent_result(case))
    if args.check_record:
        if json.loads(RESULT_FILE.read_text()) != expected:
            raise ValueError('Recorded filter decision differs from the independent support check')
        print('Recorded selections match all nine independent support checks (standard library).')
        return
    actual = record(native_result(case))
    if actual != expected:
        raise ValueError('Native filter disagrees with independent support check')
    if args.write:
        RESULT_FILE.write_text(json.dumps(actual, indent=2) + '\n')
    elif json.loads(RESULT_FILE.read_text()) != actual:
        raise ValueError('The new Semantica run differs from the published receipt')
    print('Semantica 0.7.0 reproduced all nine selections across five claims.')


if __name__ == '__main__':
    main()
