#!/usr/bin/env python3
"""Compare full-wire digests/shapes, never disclose natural dictionary bodies."""
import importlib.util
import json
from pathlib import Path
import re
import sys
here = Path(__file__).resolve().parent
spec = importlib.util.spec_from_file_location('strict', here.parents[2] / 'work/2026-09-28-smart-canteen-dm8-poc/http-harness/strict_response_compare.py')
strict = importlib.util.module_from_spec(spec)
spec.loader.exec_module(strict)
expected = ['PILOT_DICT_NATION_1', 'PILOT_DICT_NATION_2', 'PILOT_DICT_SPORT_1', 'PILOT_DICT_SPORT_2']

def checked(path, lane):
    data = strict.load_json(path)
    assert data['lane'] == lane and data['boundary_verified'] is True and data['existing_store_context'] == 10001
    assert data['error'] is None and data['case_count'] == len(data['cases']) == 4
    assert [c['scenario'] for c in data['cases']] == expected
    for case in data['cases']:
        assert case['method'] == 'POST' and case['http_status'] == case['business_status'] == 200
        assert case['trace_format_valid'] is True and case['full_source_projection_equal'] is True
        assert case['source_rows'] > 0 and case['returned_root_rows'] > 0 and case['dictionary_dml'] == 0
        assert re.fullmatch(r'[0-9a-f]{64}', case['complete_wire_sha_without_trace'])
        assert case['raw_json_shape']['object']['data']['object']['list']['array']
    assert data['cases'][0]['complete_wire_sha_without_trace'] == data['cases'][1]['complete_wire_sha_without_trace']
    assert data['cases'][2]['complete_wire_sha_without_trace'] == data['cases'][3]['complete_wire_sha_without_trace']
    assert data['cleanup'] == {'token_absent': True, 'full_natural_tables_unchanged': True,
                               'framework_dml_observed': 0, 'fixture_db_rows_created': 0}
    ends = [e for e in data['events'] if e.get('kind') == 'request_end']
    assert len(ends) == 4 and all(e['fatal'] is False for e in ends)
    return data

def main():
    b, c = checked(sys.argv[1], 'B'), checked(sys.argv[2], 'C')
    differences = strict.compare(b['cases'], c['cases'])
    lanes = {}
    sources = []
    for lane, data in [('B', b), ('C', c)]:
        queries = [e for e in data['events'] if e.get('kind') == 'query_observed']
        source = {}
        for event in queries:
            assert event['operation'] not in ['insert', 'update', 'delete', 'replace', 'merge']
            for path, sha in event.get('source_hashes', {}).items():
                assert path not in source or source[path] == sha
                source[path] = sha
        sources.append(source)
        lanes[lane] = {'queries': len(queries), 'fingerprints': len({e['fingerprint'] for e in queries}),
                       'lexical_warnings': sum(e.get('fingerprint_lexical_warning', False) for e in queries),
                       'source_snapshot': data['source_before'], 'cleanup': data['cleanup']}
    common = sources[0].keys() & sources[1].keys()
    assert common and all(sources[0][p] == sources[1][p] for p in common)
    result = {'status': 'PASS' if not differences else 'DIFFERENCE_REQUIRES_DATA_ORDER_TYPE_TRIAGE',
              'complete_wire_case_pairs': 4, 'nonempty_post_endpoints': 2,
              'complete_values_types_array_order_equal': not differences,
              'shared_source_same_sha': len(common), 'differences': differences, 'lanes': lanes,
              'proof': 'Independent complete original projections plus full canonical wire SHA; object keys canonicalized only, arrays and all values retained; only validated trace omitted'}
    print(json.dumps(result, ensure_ascii=False, indent=2, default=str))
    return bool(differences)

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