#!/usr/bin/env python3
"""One-time command evidence intake; does not create HTTP contract rows."""
import csv
import hashlib
import io
import json
import subprocess
import sys
from pathlib import Path
import integrate_20261010 as tool

HERE = Path(__file__).resolve().parent
REPORT = tool.STORE + 'parallel-onecard-cli-20261013/ROOT_REVIEW.md'
KEYS = {'store:OneCardSystemCardBackfill.php', 'store:OneCardLoginAccountBackfill.php'}

def verify():
    p = Path('/private/tmp/cdx-ai-hk-course-b.Kmdirn/review-s3-741-cli/verify_review.py')
    assert hashlib.sha256(p.read_bytes()).hexdigest() == 'fc4f5376eeb59b568206b3a7edf1e4727d2d5e1504ff70b7affaf8994de21905'
    r = json.loads(subprocess.check_output([sys.executable, '-B', str(p)]))
    assert r['offline'] and r['checks'] == 1201 and r['original_CLI'] == 8
    assert not r['full_think_tested'] and r['HTTP_coverage_increment'] == 0
    for s in 'BC':
        assert r['summary'][s]['runtime_DML'] == 0 and r['summary'][s]['exits'] == [0, 1, 0, 0]
    subprocess.check_call(['git', '-C', str(tool.source_root('store')), 'merge-base', '--is-ancestor', r['source_commit'], 'develop_dameng'])

if __name__ == '__main__':
    audit = HERE / 'integration-20261013-onecard-cli.json'
    assert not audit.exists(), 'Never replay main'
    verify()
    assert (tool.ROOT / REPORT).is_file()
    headers, rows, raw = tool.read_csv(tool.COVERAGE)
    previous = []
    for row in rows:
        if row['kind'] == 'command' and row['repo'] == 'store' and row['route_or_command'] in KEYS:
            previous.append(dict(row))
            row.update(risk='local-dryrun-only-no-apply-no-funds',
                db_access_review='original-Command-Service-SQL-owned-business-only',
                mysql_http_or_command='partial-evidence-minimal-original-Console-dryrun-not-full-think',
                dm_http_or_command='partial-evidence-minimal-original-Console-dryrun-not-full-think',
                database_readback='tested-pass-complete-owned-maps-unchanged-runtime-DML0',
                external_stub='network-hard-denied-no-real-onecard',
                evidence=tool.append_evidence(row['evidence'], REPORT))
    assert len(previous) == 2 and {r['route_or_command'] for r in previous} == KEYS
    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)
    new = out.getvalue().encode()
    assert tool.COVERAGE.read_bytes() == raw, 'Concurrent matrix writer'
    tool.COVERAGE.write_bytes(new)
    result = {'commands': sorted(KEYS), 'HTTP_increment': 0, 'scope': 'limited original Console dryrun only',
              'old_rows': previous, 'before_sha256': hashlib.sha256(raw).hexdigest(), 'after_sha256': hashlib.sha256(new).hexdigest(), 'evidence': REPORT}
    audit.write_text(json.dumps(result, ensure_ascii=False, indent=2) + '\n')
    print(json.dumps({'updated_commands': 2, 'HTTP_increment': 0, 'full_think_tested': False}))
