#!/usr/bin/env python3
"""Recover one historical source owner without inventing missing raw/DB evidence."""
import csv
import hashlib
import io
import json
import subprocess
import sys
from pathlib import Path
import integrate_20261010 as tool

REPORT = tool.STORE + 'parallel-old-evaluate-detail-20261013/ROOT_REVIEW.md'
PATH = '/api/orderEvaluate/detail'

def verify():
    p = tool.ROOT.parent / 'worktrees/dm8-compat-20261012/private-prepay-harness/review-old-order-evaluate-detail/verify_review.py'
    assert hashlib.sha256(p.read_bytes()).hexdigest() == '1f618379a8fdf2809127babba8544d4593fa3e3391c428546c3bcb75bd14638d'
    r = json.loads(subprocess.check_output([sys.executable, '-B', str(p)]))
    assert r['offline'] and r['checks'] == 36 and r['old_is_ancestor']
    assert not r['full_compatibility_pass'] and not r['live_environment_independently_confirmed']
    assert r['new_SQL_HTTP_calls'] == 0 and r['path'] == PATH and r['method'] == 'POST'
    assert len(r['source_closure_same']) == 18

if __name__ == '__main__':
    audit = Path(__file__).with_name('integration-20261013-old-evaluate.json')
    assert not audit.exists(), 'Never replay main'
    verify(); assert (tool.ROOT / REPORT).is_file()
    pending = []; old = []
    for file, column in [(tool.COVERAGE, 'route_or_command'), (tool.CONTRACT, 'path')]:
        headers, rows, raw = tool.read_csv(file)
        selected = [r for r in rows if r['method'] == 'POST' and r[column].lower() == PATH.lower()]
        assert len(selected) == 1 and selected[0]['repo'] == 'unreviewed'
        r = selected[0]; old.append({'file': str(file.relative_to(tool.ROOT)), 'row': dict(r)})
        r.update(repo='store', source='historical-summary-and-source-owner-recovered-from-apifox',
            evidence=tool.append_evidence(r['evidence'], REPORT))
        if column == 'route_or_command':
            r.update(db_access_review='historic-source-read-chain-known-runtime-environment-pin-unavailable',
                mysql_http_or_command='partial-evidence-limited-historical-HTTP200-code0-summary-no-raw',
                dm_http_or_command='partial-evidence-limited-historical-HTTP200-code0-summary-no-raw',
                database_readback='not-recovered-original-PDO-rows-and-execution-identity',
                external_stub='historical-readonly-runner-design-not-live-verified')
        else:
            r.update(delivery_scope='historical-source-route-recovered-not-full-acceptance',
                reachability='historically-reported-POST-only-not-replayed',
                db_scope='reported-local-MySQL-and-nonproduction-DM-execution-pins-incomplete',
                success_case='partial-evidence-limited-historical-summary-only',
                mysql_input_and_readback='not-recovered-actual-selected-id-raw-and-original-row',
                dm_input_and_readback='not-recovered-actual-selected-id-raw-and-original-row',
                response_parity='not-compared-full-JSON-identity-only-string-coerced-historical-check',
                fixture='historical-per-database-natural-sample-actual-IDs-not-recovered',
                cleanup='read-only-historical-report-no-new-execution', coverage_gate='open')
        out = io.StringIO(newline='')
        writer = csv.DictWriter(out, fieldnames=headers, lineterminator='\r\n' if b'\r\n' in raw else '\n')
        writer.writeheader(); writer.writerows(rows)
        pending.append((file, raw, out.getvalue().encode()))
    assert all(f.read_bytes() == raw for f, raw, _ in pending), 'Concurrent matrix writer'
    for f, _, new in pending: f.write_bytes(new)
    audit.write_text(json.dumps({'path': PATH, 'old_rows': old, 'new_keys': 0, 'new_live_tests': 0,
        'evidence': REPORT, 'classification': 'limited-historical-summary-not-full-compatibility'},
        ensure_ascii=False, indent=2) + '\n')
    print(json.dumps({'source_owner_recovered': 1, 'new_keys': 0, 'new_live_tests': 0, 'full_pass': False}))
