#!/usr/bin/env python3
"""Enhance existing command evidence; no HTTP rows or functional apply claims."""
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-full-think-861-921-20261013/ROOT_REVIEW.md'
KEYS = {'store:OneCardSystemCardBackfill.php', 'store:OneCardLoginAccountBackfill.php'}

def verify():
    p = tool.ROOT.parent / 'worktrees/dm8-compat-20261012/private-prepay-harness/review-s3-861-921-fullthink/verify_independent.py'
    assert hashlib.sha256(p.read_bytes()).hexdigest() == 'f10423151778573e8cae09097f93c1e824b4e33319648218fcbd900456f9bee2'
    r = json.loads(subprocess.check_output([sys.executable, '-B', str(p)]))
    assert r['passed'] and r['checks'] == 738
    assert r['fullthink_attempts'] == 5 and r['actual_target_executions'] == 4
    assert r['SQL_attempts'] == 103 and r['blocked_before_database'] == 1
    assert r['new_DB'] == r['new_HTTP'] == r['new_business_CLI'] == 0
    subprocess.check_call(['git', '-C', str(tool.source_root('store')), 'merge-base', '--is-ancestor',
        '1ece999a95f382f7f1a0ffc8874b6bb14f6afcb9', 'develop_dameng'])

if __name__ == '__main__':
    audit = Path(__file__).with_name('integration-20261013-full-think.json')
    assert not audit.exists(), 'Never replay main'
    verify()
    assert (tool.ROOT / REPORT).is_file()
    headers, rows, raw = tool.read_csv(tool.COVERAGE)
    old = []
    for row in rows:
        if row['kind'] != 'command' or row['repo'] != 'store' or row['route_or_command'] not in KEYS:
            continue
        old.append(dict(row))
        scope = ('partial-evidence-original-full-think-nonempty-dryrun-preview-not-apply'
                 if row['route_or_command'].endswith('SystemCardBackfill.php')
                 else 'partial-evidence-original-full-think-invalid-mobile-rejection-and-native-COUNT-not-valid-repair')
        row.update(mysql_http_or_command=scope, dm_http_or_command=scope,
            database_readback='tested-pass-complete-owned-maps-and-bounded-dictionary-unchanged-no-DML',
            evidence=tool.append_evidence(row['evidence'], REPORT))
    assert len(old) == 2 and {r['route_or_command'] for r in old} == KEYS
    out = io.StringIO(newline='')
    w = csv.DictWriter(out, fieldnames=headers, lineterminator='\r\n' if b'\r\n' in raw else '\n')
    w.writeheader(); w.writerows(rows)
    new = out.getvalue().encode()
    assert tool.COVERAGE.read_bytes() == raw, 'Concurrent matrix writer'
    tool.COVERAGE.write_bytes(new)
    audit.write_text(json.dumps({'commands': sorted(KEYS), 'HTTP_increment': 0, 'old_rows': old,
        'evidence': REPORT, 'before_sha256': hashlib.sha256(raw).hexdigest(),
        'after_sha256': hashlib.sha256(new).hexdigest(), 'apply_verified': False}, ensure_ascii=False, indent=2) + '\n')
    print(json.dumps({'enhanced_existing_commands': 2, 'HTTP_increment': 0, 'apply_verified': False}))
