#!/usr/bin/env python3
"""Compare evidence scopes explicitly; never call a partial read a full API pass."""
import importlib.util
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent
spec = importlib.util.spec_from_file_location('strict_compare', HERE.parent / 'http-harness/strict_response_compare.py')
strict = importlib.util.module_from_spec(spec)
spec.loader.exec_module(strict)

def results(lane):
    rows = strict.load_json(HERE / f'store-results-{lane}.json')
    assert all(row['exit'] == 0 and row['stderr_empty'] for row in rows)
    return {(r['job'], r['result'].get('mode', 'run')): r['result'] for r in rows}

def main():
    b, c = results('B'), results('C')
    device = ('device_recipes_run.php', 'run')
    differences = strict.compare(b[device]['response_contracts'], c[device]['response_contracts'])
    assert len(b[device]['response_contracts']) == len(c[device]['response_contracts']) == 9
    assert not differences, [(p, e, a) for p, e, a, _, _ in differences]
    for lane in (b, c):
        assert lane[device]['source_and_target_rows_after_cleanup'] == 0
        assert lane[device]['dish_quantity_restored'] is True
        assert lane[device]['second_slot_failure_full_state_rollback'] is True
        assert lane[('device_recipes_run.php', '--audit')]['remaining_test_window_device_recipes'] == 0
        order = lane[('meal_wide_run.php', '--run')]
        assert order['field_json_type'] == 'integer' and order['field_json_value'] == '9007199254740993'
        assert order['cleaned'] is True and order['field_exact'] is True
        audit = lane[('meal_wide_run.php', '--audit')]
        assert audit['own_order_count'] == 0 and audit['source_type_after'] == 1
        recipes = lane[('recipes_run.php', 'run')]
        assert recipes['all_returned_dishes_match_source'] is True
        assert recipes['source_unchanged'] is True and recipes['actor_rows_after'] == 0
    assert b[('recipes_run.php', 'run')]['data_shape_sha'] == c[('recipes_run.php', 'run')]['data_shape_sha']
    print(json.dumps({'status': 'passed', 'device_recipe_response_cases': 9,
        'device_response_differences': len(differences), 'device_db_readback_and_cleanup': True,
        'order_scope': 'exact wide identifier plus cleanup, not full detail response',
        'recipes_scope': 'natural-source membership and response shape, unequal snapshots not value-equivalent'}))

if __name__ == '__main__':
    main()
