#!/usr/bin/env python3
"""Audited menu projections and own-device pairing; retain wrong-URL failure."""
import hashlib
import json
import subprocess
import sys
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

HERE = Path(__file__).resolve().parent
PRIVATE = Path('/private/tmp/cdx-ai-hk-course-b.Kmdirn')
REPORT = tool.STORE + 'parallel-nutrients-pairing-20261013/ROOT_REVIEW.md'
CHECKS = [
    ('review-s1-461-471/verify_review.py', '24a1105d7153c1af71a4cca8b5882c28c64e346ab6f01028d1b0bdd9cd62580a', 4102, 'store', '75cdca99fc05edc666cfa7d0af8aa5235a03d74a'),
    ('review-s2-541-555/verify_review.py', '29f7a145d13288cfda7a84a2b43f9e567d7a9a802f4473df8b1f618912ba2116', 468, 'ai_api', 'b4dc2778b8a783652ab4119eb33d87cd48e299d6'),
]


def verify():
    for relative, digest, count, repo, revision in CHECKS:
        path = PRIVATE / relative
        assert hashlib.sha256(path.read_bytes()).hexdigest() == digest
        result = json.loads(subprocess.check_output([sys.executable, '-B', str(path)]))
        assert result['offline'] and result['supplemental_checks'] == count
        if repo == 'store':
            assert result['raw_business_http'] == 63 and result['failed_route'] == ['POST /m/datemenu/getmenuinfo']
            assert result['routes']['POST /m/date_menu/getmenuinfo'] == 13
            for source, expected in result['source_sha256'].items():
                blob = subprocess.check_output(['git', '-C', str(tool.source_root(repo)), 'show', revision + ':' + source])
                assert hashlib.sha256(blob).hexdigest() == expected
        else:
            assert result['business_http'] == 16 and result['writes'] == 4 and result['pure_checks'] == 40
            blob = subprocess.check_output(['git', '-C', str(tool.source_root(repo)), 'show', revision + ':app/terminal/service/equipment/Equipment.php'])
            assert hashlib.sha256(blob).hexdigest() == result['source'][1]['service']
        subprocess.check_call(['git', '-C', str(tool.source_root(repo)), 'merge-base', '--is-ancestor', revision, 'develop_dameng'])


if __name__ == '__main__':
    audit = HERE / 'integration-20261013-nutrients-pairing.json'
    assert not audit.exists(), 'Never replay main'
    rows = [item('store', 'POST', '/p/datemenu/' + action, '', evidence=REPORT, evidence_only=True)
            for action in ['editMenu', 'getMenuInfo', 'getMenu']]
    rows.append(item('store', 'POST', '/m/date_menu/getmenuinfo', '', evidence=REPORT,
        register_new_runtime_key=True, runtime_observed_method='POST',
        runtime_inventory_scope='controller-direct-http-observed', runtime_direct_http_proof=REPORT,
        runtime_controller_source='application/m/controller/DateMenu.php:29 real-default-dispatch-underscore-path-no-current-client-claim',
        success_case='partial-evidence-original-mobile-nutrition-typed-projections-empty-and-type3-read-only',
        readback='tested-pass-own-complete-native-menu-source-and-full-JSON-decimal-scales',
        parity='partial-evidence-correct-underscore-URL-original-unseparated-URL-C404-retained'))
    rows.append(item('ai_api', 'GET', '/terminal/equipment/matecode', '', evidence=REPORT,
        success_case='partial-evidence-original-own-fake-device-pairing-and-repeat-rejections',
        readback='tested-pass-complete13-native-device-fields-own-Store-and-zero-message-protection',
        parity='partial-evidence-full-JSON-types-values-private-config-fixture-no-real-MQTT',
        cleanup='fresh-owned-Store-device-records-retained-private-cache-workers-stopped-no-natural-config-rows'))
    tool.main(rows, audit, verify)
