"""Execute the version-2 teaching conditions and expose the remaining boundary."""
import hashlib
import importlib.util
import json
from pathlib import Path
from idempotent_sink import IdempotentSink

ROOT = Path(__file__).resolve().parent
CLIENT = ROOT.parent / 'v1/batchpub_after.py'
spec = importlib.util.spec_from_file_location('client', CLIENT)
client = importlib.util.module_from_spec(spec)
spec.loader.exec_module(client)


def records():
    return [{'id': 'L-101', 'payload': 'A'}, {'id': 'L-102', 'payload': 'B'}]


def run():
    pending, sink = records(), IdempotentSink()
    error = None
    try:
        client.flush(pending, sink, closed=True)
    except RuntimeError as caught:
        error = str(caught)
    first = {'pending': list(pending), 'stored': list(sink), 'error': error}
    client.flush(pending, sink, closed=True)
    same_process = {'pending': list(pending), 'stored': list(sink), 'duplicate_free': list(sink) == records()}
    conflict = None
    try:
        sink.append({'id': 'L-101', 'payload': 'different'})
    except ValueError as caught:
        conflict = str(caught)
    sink.forget_dedup_state()
    client.flush(records(), sink, closed=True)
    after_reset = {'stored': list(sink), 'duplicate_free': len(sink) == 2}
    return {
        'scope': 'In-process teaching fixtures only; no real network, disk persistence, or product acceptance.',
        'files': {str(path.relative_to(ROOT.parent)).replace('\\','/'): hashlib.sha256(path.read_bytes()).hexdigest()
                  for path in [CLIENT, ROOT/'idempotent_sink.py', ROOT/'probe_dedup.py']},
        'first_attempt': first,
        'same_receiver_retry': same_process,
        'id_conflict': conflict,
        'after_dedup_reset': after_reset,
    }


if __name__ == '__main__':
    print(json.dumps(run(), indent=2, ensure_ascii=False))
