#!/usr/bin/env python3
"""One-time intake of six article/annex keys and the staff response fix."""
import hashlib
import json
import subprocess
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item
from integrate_20261013_batches221_223_224_226 import shape

HERE = Path(__file__).resolve().parent
PHP = '/opt/homebrew/opt/php@7.4/bin/php'
REVIEW = Path('/private/tmp/cdx-ai-hk-course-b.Kmdirn/review-store-261-267')
STAFF = tool.ROOT.parent / 'worktrees/dm8-compat-20261012/private-prepay-harness/batch274-api-info-time'
ARTICLE_REPORT = tool.STORE + 'parallel-article-annex-bundle-20261013/ROOT_REVIEW.md'
STAFF_REPORT = tool.STORE + 'parallel-api-info-time-20261013/ROOT_REVIEW.md'


def pin(path, expected):
    assert hashlib.sha256(path.read_bytes()).hexdigest() == expected, path.name


def verify():
    pin(REVIEW / 'verify_store_bundle.php', 'eaf3e0a0898a585a6e603e6eb1b07686fadc991b61f6f60ae521ddf1a205e785')
    pin(REVIEW / 'MANIFEST.json', '33b69af94b1d991de6fc10580212d835e9ae05bcdac481c586ea427486bf3f10')
    result = json.loads(subprocess.check_output([PHP, str(REVIEW / 'verify_store_bundle.php')]))
    assert result['supplement_checks'] == 1980 and result['manifest_assets'] == 252
    assert len(result['proposed_keys']) == 6 and result['original_HTTP'] == {'B': 15, 'C': 16}
    for name, sha in {
        'REPORT274.md': 'd982b4da20a60c91de2d77d0326b270463a1028babf5b3f8515762fe88f2daf4',
        'verify274.php': '3a577cbb3e20aa7044ac367b5800138749a49bcdae1e007e5338b10660c5411b',
        'manifest274.json': 'd295d528cd65701c7a557336858a41df528e9a15edadd46f2591fb6ff8f607eb',
    }.items():
        pin(STAFF / name, sha)
    assets = json.loads((STAFF / 'manifest274.json').read_text())['assets']
    assert len(assets) == 87
    for asset in assets:
        relative = Path(asset['path'])
        assert not relative.is_absolute() and '..' not in relative.parts
        path = STAFF / relative
        assert path.stat().st_size == asset['bytes']
        pin(path, asset['sha256'])
    result = json.loads(subprocess.check_output([PHP, str(STAFF / 'verify274.php')]))
    assert result['passed'] and result['assertions'] == 421 and result['fields_each'] == 80
    for lane in ('B', 'C'):
        side = STAFF / ('execution-' + lane)
        intent = json.loads((side / 'intent274.json').read_text())
        assert intent['method'] == 'POST' and intent['path'] == '/p/api/info'
        wire = json.loads((side / 'wire274.json').read_text())
        raw = json.loads((side / 'response274.raw').read_text())
        assert wire['http'] == 200 and raw == wire['json'] and shape(raw) == shape(wire['json'])
    source = subprocess.check_output(['git', '-C', str(tool.source_root('store')), 'show',
        '5a4ea2090b48d1a317e4da0477032b26629dd0ea:application/p/logic/Api.php'])
    assert hashlib.sha256(source).hexdigest() == '6fa62597dcd2d2ec408642eb00d3df3aca89c7d7a17975775d6748d29495d8a2'
    subprocess.check_call(['git', '-C', str(tool.source_root('store')), 'merge-base', '--is-ancestor',
        '5a4ea2090b48d1a317e4da0477032b26629dd0ea', 'develop_dameng'])


if __name__ == '__main__':
    audit = HERE / 'integration-20261013-article-staff-bundle.json'
    assert not audit.exists(), 'Never replay integration main'
    rows = [item('store', 'POST', path, '', evidence=ARTICLE_REPORT,
        success_case='partial-evidence-original-owned-CRUD-complete-native-row-and-JSON-contract',
        request_type='application/x-www-form-urlencoded',
        readback='tested-pass-independent-original-full-row-before-after-and-SQL-nonce-chain',
        boundary_empty_min_max='see-report-original-noop-code1-date-zero-fraction-short-fourbyte-absent-file-only',
        cleanup='original-owned-fixtures-deleted-no-natural-data-or-real-files-deleted')
        for path in ['/p/article/update', '/p/article/info', '/p/article/delete', '/p/article/able',
                     '/p/materialAnnex/delete', '/p/trainannex/delannex']]
    rows.append(item('store', 'POST', '/p/api/info', '', evidence=STAFF_REPORT,
        role='original-plain-controller-no-login-claim', request_type='application/x-www-form-urlencoded',
        success_case='partial-evidence-owned-full80-source-fields-and-zero-fraction-time-regression',
        readback='tested-pass-full77-physical-row-and-joined-source-unchanged-exact-UINT64',
        parity='partial-evidence-B-wire-unchanged-C-only-create_time-zero-fraction-fixed-fixture-values-differ',
        cleanup='no-business-writes-private-worker-stopped-old-owned-rows-retained'))
    tool.main(rows, audit, verify)
