#!/usr/bin/env python3
"""Classify three preflight-blocked existing source routes; no HTTP acceptance."""
import hashlib
import csv
import io
import json
import subprocess
import sys
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

def verify():
    p = tool.ROOT.parent / 'worktrees/dm8-compat-20261012/private-prepay-harness/review-nutrition1301-1341/verify.py'
    assert hashlib.sha256(p.read_bytes()).hexdigest() == '1641139e63367005245277e8a3f2a7f69b37039c3fb65db904844143319dc165'
    r = json.loads(subprocess.check_output([sys.executable, '-B', str(p)]))
    assert r['passed'] and r['independent_checks'] == 387
    assert r['new_SQL'] == r['new_HTTP'] == r['HTTP_interfaces_tested'] == 0
    assert r['1341_attempts'] == {'B': 4, 'C': 6}

def finalize_source_only(audit):
    record = json.loads(audit.read_text())
    assert 'source_only_finalization' not in record, 'Already finalized'
    paths = {'/m/nutrition/' + x for x in ('programmelists', 'programmedetail', 'shareprogrammedetail')}
    pending, notes = [], []
    for file, key in [(tool.COVERAGE, 'route_or_command'), (tool.CONTRACT, 'path')]:
        headers, rows, raw = tool.read_csv(file)
        selected = [r for r in rows if r['repo'] == 'store' and r['method'] == 'POST' and r[key].lower() in paths]
        assert len(selected) == 3
        for row in selected:
            row['source'] = 'source-owner-verified-preflight-blocked-no-HTTP'
            if key == 'path':
                row['reachability'] = 'source-only-Controller-not-runtime-observed'
                row['request_types'] = 'source-POST-not-executed'
                row['fixture'] = 'none-created-no-business-rows-read'
            else:
                row['external_stub'] = 'no-HTTP-or-external-execution'
        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()
        pending.append((file, raw, new))
        notes.append({'file': str(file.relative_to(tool.ROOT)), 'before': hashlib.sha256(raw).hexdigest(), 'after': hashlib.sha256(new).hexdigest()})
    assert all(p.read_bytes() == raw for p, raw, _ in pending), 'Concurrent writer'
    for p, _, new in pending: p.write_bytes(new)
    for resolution in record['ownership_resolution']:
        resolution['meaning'] = 'Source Controller ownership established; only preflight/native zero-row diagnostics executed. No HTTP reachability or response verified.'
    record['source_only_finalization'] = notes
    audit.write_text(json.dumps(record, ensure_ascii=False, indent=2) + '\n')

if __name__ == '__main__':
    audit = Path(__file__).with_name('integration-20261014-nutrition1341.json')
    if sys.argv[1:] == ['--finalize-source-only']:
        finalize_source_only(audit)
        sys.exit(0)
    assert not audit.exists(), 'Never replay main'
    report = 'work/2026-09-28-smart-canteen-dm8-poc/matrix-integration/ROOT_NUTRITION1341_BLOCKED_20261014.md'
    specs = [item('store', 'POST', '/m/nutrition/' + action, '', evidence=report,
        from_repo='unreviewed', from_source='apifox-2026-05-08',
        scope='source-owned-nutrition_app-current-approved-object-not-resolved',
        mysql_state='blocked-env-object-not-resolved-no-HTTP',
        dm_state='blocked-env-object-not-resolved-no-HTTP',
        success_case='not-tested', mysql_readback='not-tested-business-rows',
        dm_readback='not-tested-business-rows', readback='not-tested',
        parity='not-compared-no-original-HTTP', performance='environment-blocked-object-not-resolved',
        delivery_scope='source-owned-delivery-usage-unconfirmed',
        cleanup='zero-HTTP-fixtures-writes-no-runtime-started') for action in ('programmeLists', 'programmeDetail', 'shareProgrammeDetail')]
    tool.main(specs, audit, verify)
    finalize_source_only(audit)
