#!/usr/bin/env python3
"""Intake diet token fix with ON UPDATE failure retained, logout and limited file."""
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
BASE = tool.ROOT.parent / 'worktrees/dm8-compat-20261012/private-prepay-harness'
PHP = '/opt/homebrew/opt/php@7.4/bin/php'
REPORT = tool.STORE + 'parallel-diet-logout-download-20261013/ROOT_REVIEW.md'


def verify():
    checks = [
        (PHP, BASE / 'review-diet283-independent/verify_review.php', '41b98df12c6b1729d9ea87ad8945f4b413c086d30b8db8308795dfe3a86c5274', 'checks', 17460),
        (PHP, BASE / 'review-284-286-resume/review.php', '96a01597bf161bbd065686a16a855f3ee222909a0b524e150c2b31204caffc27', 'offline_independent_checks', 431),
        (sys.executable, Path('/private/tmp/cdx-ai-hk-course-b.Kmdirn/review-store-278-282/verify_review.py'), '95d11531b08b626ccce5351eafc307e3df1f6d70b88537bc1661ae953155dd59', 'checks', 2053),
    ]
    for executable, script, digest, field, count in checks:
        assert hashlib.sha256(script.read_bytes()).hexdigest() == digest
        args = [executable] + (['-B'] if executable == sys.executable else []) + [str(script)]
        result = json.loads(subprocess.check_output(args))
        assert result[field] == count and not result.get('failures', [])
    receipt = json.loads(subprocess.check_output([PHP, str(BASE / 'batch283-diet-token-regression/verify283.php')]))
    assert receipt['checks'] == 1694 and not receipt['failures'] and receipt['ON_UPDATE_gap_still_open']
    source = subprocess.check_output(['git', '-C', str(tool.source_root('store')), 'show', 'develop_dameng:application/p/logic/DietRecord.php'])
    assert hashlib.sha256(source).hexdigest() == '5f9a408f08bae1390a5b411efb874026f5bd0340d4a41c686dc13869ba56e273'
    subprocess.check_call(['git', '-C', str(tool.source_root('store')), 'merge-base', '--is-ancestor', '86273a0e8acf902d228e39654da1dd081a3b2fa6', 'develop_dameng'])


if __name__ == '__main__':
    audit = HERE / 'integration-20261013-diet-logout-download.json'
    assert not audit.exists(), 'Never replay main'
    rows = [item('store', 'POST', '/p/ontoanalysis/FoodRecordExport', '', evidence=REPORT,
        success_case='partial-evidence-original-single-owned-day-XLSX-each80cells-and42-nutrients',
        readback='tested-pass-native-source-unchanged-C-private-same-version-dependency-repair-only',
        parity='partial-evidence-independent-source-XLSX-cell-types-values-formulas-not-multi-image')]
    rows.append(item('store', 'POST', '/p/ontoanalysis/FoodRecordUploads', '', evidence=REPORT, evidence_only=True))
    rows.append(item('store', 'POST', '/p/ontoanalysis/FoodRecordUpdate', '', evidence=REPORT,
        mysql_state='tested-pass-original-four-updates-and-stale-token-rollback',
        dm_state='tested-fail-meal-infos-automatic-update-time-not-advanced-other-four-updates-and-stale-rollback-pass',
        success_case='failed-open-ON-UPDATE-semantic-gap-despite-positive-persistence-and-fixed-token',
        readback='tested-fail-native-detail-timestamp-unchanged-while-other-values-persist-correctly',
        parity='failed-open-detail-ON-UPDATE-no-concurrency-completion-claim'))
    rows.append(item('store', 'POST', '/p/login/logout', '', evidence=REPORT,
        success_case='partial-evidence-original-logout-audit-I1-native20columns-private-cache-cookie',
        readback='tested-pass-full-new-audit-row-old-set-hash-protection-not-new-physical-requery',
        parity='partial-evidence-full-JSON-types-values-original-private-session-only'))
    rows.append(item('store', 'GET', '/p/download/zip', '', evidence=REPORT,
        mysql_state='partial-evidence-file-and-shared-init-only', dm_state='partial-evidence-file-and-shared-init-only',
        success_case='partial-evidence-limited-original68bytes-file-and-shared-config-init',
        readback='partial-evidence-six-config-rows-unchanged-no-independent-domain-write',
        parity='partial-evidence-limited-file-bytes-headers-not-database-utf8mb4-write'))
    tool.main(rows, audit, verify)
