#!/usr/bin/env python3
"""Correct progress-token granularity for batch 104 without replacing its audit."""
import csv
import hashlib
import io
import json
from pathlib import Path

HERE = Path(__file__).resolve().parent
ROOT = HERE.parents[2]
FILES = [
    ROOT / 'work/2026-09-28-smart-canteen-dm8-poc/http-cron-coverage-matrix.csv',
    ROOT / 'work_store/apifox/2026-09-30-dm8-interface-acceptance/derived/interface-contract-matrix.csv',
]
AUDIT = HERE / 'integration-20261011-batch104-status-correction.json'
KEY = ('ai_api', 'POST', '/store/order.Event/updateRemark')


def sha(data):
    return hashlib.sha256(data).hexdigest()


def main():
    assert not AUDIT.exists(), 'Preserve prior correction evidence'
    pending = []
    for path in FILES:
        raw = path.read_bytes()
        rows = list(csv.DictReader(io.StringIO(raw.decode('utf-8'), newline='')))
        matches = [r for r in rows if (r.get('repo'), r.get('method'), r.get('route_or_command', r.get('path'))) == KEY]
        assert len(matches) == 1, f'Expected one exact matrix key in {path}'
        row = matches[0]
        before = dict(row)
        if 'route_or_command' in row:
            assert row['mysql_http_or_command'].startswith('tested-pass-')
            assert row['dm_http_or_command'].startswith('tested-pass-')
            row['mysql_http_or_command'] = 'tested-pass'
            row['dm_http_or_command'] = 'tested-pass'
        else:
            assert row['mysql_input_and_readback'].startswith('tested-pass-')
            assert row['dm_input_and_readback'].startswith('tested-pass-')
            # Keep the detailed native readback prose; classification reads the
            # exact HTTP pass tokens from the coverage matrix.
        fields = list(matches[0].keys())
        stream = io.StringIO(newline='')
        writer = csv.DictWriter(stream, fieldnames=fields, lineterminator='\r\n' if b'\r\n' in raw else '\n')
        writer.writeheader(); writer.writerows(rows)
        new = stream.getvalue().encode('utf-8')
        pending.append((path, raw, new, before, dict(row)))
    if any(path.read_bytes() != raw for path, raw, *_ in pending):
        raise RuntimeError('Concurrent matrix writer detected')
    for path, _, new, *_ in pending:
        if path.read_bytes() != new:
            path.write_bytes(new)
    audit = {'scope': 'evidence-token normalization only; no acceptance change', 'key': KEY,
        'reason': 'Detailed tested-pass suffix did not satisfy exact tested-pass dual-engine progress gate; normalize only exact per-engine status tokens.',
        'files': [{'path': str(path.relative_to(ROOT)), 'before_sha256': sha(raw), 'after_sha256': sha(new),
            'before_row': before, 'after_row': after} for path, raw, new, before, after in pending]}
    AUDIT.write_text(json.dumps(audit, ensure_ascii=False, indent=2) + '\n')
    print(json.dumps({'changed_files': sum(raw != new for _, raw, new, *_ in pending),
        'audit': str(AUDIT.relative_to(ROOT))}))


if __name__ == '__main__':
    main()
