#!/usr/bin/env python3
"""Root-only integration of Store Article missing-row limited branches."""
import hashlib
import json
from pathlib import Path
import subprocess

import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

HERE = Path(__file__).resolve().parent
PRIVATE = Path('/Users/wiscourper/Documents/workspace/local/dm8-store-article-negative-actual-20261011.GKQsMB')
EVIDENCE = 'work_store/apifox/2026-09-30-dm8-interface-acceptance/parallel-store-article-negative-20261011/ROOT_REVIEW_ARTICLE_NEGATIVE_20261011.md'


def verify():
    assert (tool.ROOT / EVIDENCE).is_file()
    manifest_bytes = (PRIVATE / 'manifest.json').read_bytes()
    assert hashlib.sha256(manifest_bytes).hexdigest() == '020213b2c83735bfcdf6244a50a7f8ca563a9a655c9cb0bc8e7beca738dc2bd1'
    result = json.loads(subprocess.run(['node', str(PRIVATE / 'verify-final.js'), '--readonly'],
        check=True, capture_output=True, text=True).stdout)
    assert result['readonly'] and result['checks'] == 586 and result['files'] == 207
    assert result['HTTP'] == 4 and result['DML'] == 0 and result['negative_limited_only']
    derived = json.loads((PRIVATE / 'verification.json').read_text())
    assert derived['negative_limited_only'] and derived['raw_business_fetch_event_captured'] is False
    for side, expected_old, expected_total, expected_pre in [('B', 1079, 1112, 10), ('C', 1331, 1375, 11)]:
        lane = derived['lanes'][side]
        assert lane['new_reads'] + expected_old == lane['total_reads'] == expected_total
        assert lane['preflight'] == expected_pre and lane['independent_absence0']
        assert lane['original_PDO_SELECT_rowCount'] == ({'A1': 0, 'A2': 0} if side == 'B' else {'A1': -1, 'A2': -1})
        assert lane['own_cache_entries_removed'] == 1 and lane['worker_stopped']


def targets():
    base = EVIDENCE.rsplit('/ROOT_REVIEW', 1)[0] + '/'
    out = []
    for path, scenario in [('/p/article/able', 'missing-row-status-change-rejected-before-write'),
                           ('/p/article/update', 'multipart-empty-files-missing-row-rejected-before-category-or-upload')]:
        out.append(item('store', 'POST', path, base, evidence=EVIDENCE,
            from_source='current-PC-client-and-controller-route-source', terminal='PC-publish-information',
            role='existing-marked-type0-operator-original-auth', risk='article-missing-row-negative-only',
            scope='store-primary-exact-synthetic-absent-uuid-no-natural-article-row',
            request_type='original-form-or-multipart-scalar-uuid-no-file-parts',
            success_case='partial-evidence-limited-negative-' + scenario,
            mysql_state='tested-pass-empty-only', dm_state='tested-pass-empty-only',
            readback='limited-successful-bound-SELECT-and-independent-before-after-absence;raw-fetch-event-not-captured',
            parity='limited-original-negative-wire-matches; DM SELECT rowCount=-1 retained as unknown, not zero',
            cleanup='no-business-write-worker-token-private-cache-released',
            missing_required='not-tested', invalid_type='not-tested', duplicate_retry='not-tested',
            boundary_empty_min_max='partial-evidence-native-query-success-original-no-row-error-envelope-only',
            performance='not-tested'))
    return out


if __name__ == '__main__':
    audit = HERE / 'integration-20261011-batch100.json'
    assert not audit.exists(), 'Preserve previous integration evidence'
    tool.main(targets(), audit, verify)
