#!/usr/bin/env python3
"""Root-only integration of Store Read2 and AI Foods owned CRUD evidence."""
import hashlib
import json
from pathlib import Path
import subprocess
import sys

import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

HERE = Path(__file__).resolve().parent
STORE_PRIVATE = Path('/Users/wiscourper/Documents/workspace/local/dm8-store-read2-actual-20261011.CGDfJj')
AI_PRIVATE = Path('/Users/wiscourper/Documents/workspace/local/dm8-ai-foods-owned-exec-20261011.o1xViQ')
STORE_EVIDENCE = 'work_store/apifox/2026-09-30-dm8-interface-acceptance/parallel-store-read2-20261011/ROOT_REVIEW_WEEK_PREVIEW_20261011.md'
AI_EVIDENCE = 'work_ai_api/2026-09-30-dm8-interface-acceptance/parallel-ai-foods-add-delete-20261011/ROOT_REVIEW_FOODS_ADD_DELETE_20261011.md'


def verify():
    assert (tool.ROOT / STORE_EVIDENCE).is_file() and (tool.ROOT / AI_EVIDENCE).is_file()
    store = json.loads(subprocess.run(['node', str(STORE_PRIVATE / 'verify-final.js'), '--readonly'],
        check=True, capture_output=True, text=True).stdout)
    assert store['readonly'] and store['checks'] == 626 and store['seal_files'] == 166
    assert store['HTTP'] == 4 and store['DML'] == 0 and store['all_hash_bytes_modes']
    sm = json.loads((STORE_PRIVATE / 'verification.json').read_text())
    assert hashlib.sha256((STORE_PRIVATE / 'manifest.json').read_bytes()).hexdigest() == '5d02310d9c8d89682c204f52f8e5cc38af33c2f96b07094f0ba784efebf27976'
    assert sm['actual_HTTP_per_side'] == 2 and sm['task_endpoint_HTTP'] == 0
    assert sm['lanes']['B']['new_reads'] == 65 and sm['lanes']['C']['new_reads'] == 87

    ai = json.loads(subprocess.run([sys.executable, '-B', str(AI_PRIVATE / 'verify.py')],
        check=True, capture_output=True, text=True).stdout)
    assert ai['pass'] and ai['assets'] == 144 and ai['audit']['pass'] and ai['audit']['checks'] == 13518
    assert ai['DB'] == ai['HTTP'] == 0
    am = json.loads((AI_PRIVATE / 'MANIFEST.json').read_text())
    assert hashlib.sha256((AI_PRIVATE / 'MANIFEST.json').read_bytes()).hexdigest() == 'c76e3ef4b738b981e95d168447adbfc31aec6800ea58f8fa0f299bf956dc67fd'
    assert all(ai['audit']['summary'][s]['HTTP'] == 2 and ai['audit']['summary'][s]['INSERT'] == 1
        and ai['audit']['summary'][s]['soft_UPDATE'] == 1 and ai['audit']['summary'][s]['whole_row55']
        for s in ['B', 'C'])
    assert all(ai['audit']['summary'][s]['parent_PDO_ID_php_type'] == 'string'
        and ai['audit']['summary'][s]['wire_JSON_ID_type'] == 'string' for s in ['B', 'C'])
    assert ai['audit']['physical_precision_equal'] is False and ai['audit']['known_datetime_P0_not_closed']


def targets():
    store_base = STORE_EVIDENCE.rsplit('/ROOT_REVIEW', 1)[0] + '/'
    ai_base = AI_EVIDENCE.rsplit('/ROOT_REVIEW', 1)[0] + '/'
    out = [item('store', 'POST', '/p/bill/weekCopyPreview', store_base, evidence=STORE_EVIDENCE,
        from_source='current-client-route-source', terminal='PC-restaurant-management', role='existing-marked-type0-operator',
        risk='readonly-week-preview-with-private-cache-only', scope='store-primary-source-week-recipe-and-dish-projection-current-restaurant',
        request_type='original-form-POST-json-string-arrays',
        success_case='partial-evidence-nonempty-week-preview-B4-C62-Copy46-Skip16-original-disabled-rule',
        mysql_state='tested-pass', dm_state='tested-pass',
        readback='tested-pass-full-per-engine-source-projection-response-and-private-cache-state',
        parity='partial-evidence-original-counts-and-skip-reasons-source-backed-per-lane-snapshots-not-forced-equal',
        cleanup='readonly-business-tables-unchanged-own-preview-and-session-cache-token-worker-removed',
        missing_required='not-tested', invalid_type='not-tested', duplicate_retry='not-tested',
        boundary_empty_min_max='partial-evidence-illegal-source-date-rejected-code1-no-cache-write', performance='not-tested'),
        item('store', 'POST', '/p/cater/aiImportTaskFailNames', store_base, evidence=STORE_EVIDENCE,
        from_source='current-client-route-source', terminal='PC-dish-image-import-dialog', role='existing-marked-type0-operator',
        risk='stored-import-task-failure-result-read-sensitive-payload-gate', scope='store-primary-current-store-task-id-and-safe-name-result-only',
        request_type='original-form-POST-task-id-string-all-integer-menu-uuid-string',
        success_case='partial-evidence-no-safe-existing-result-payload-positive-http-not-run-limited',
        mysql_state='not-tested-no-safe-payload', dm_state='not-tested-no-safe-payload',
        readback='limited-fresh-task-source-had-no-safe-result-both-engines-zero-http',
        parity='limited-no-result-payload-read-or-cross-engine-output-claim',
        cleanup='source-unchanged-no-task-created-no-file-read-token-worker-released'),
    ]
    for path, phase in [('/store/dishes.Foods/add', 'add-own-catalog-food-one-insert-per-engine'),
                        ('/store/dishes.Foods/delete', 'soft-delete-only-that-new-own-food')]:
        out.append(item('ai_api', 'POST', path, ai_base, evidence=AI_EVIDENCE,
            from_source='current-AI-Store-client-and-controller-source', terminal='AI-Store-merchant-PC',
            role='existing-authorized-marked-merchant-operator', risk='own-merchant-food-catalog-write',
            scope='ai-primary-own-tenant-foods-row-only-no-dishes-relation',
            request_type='original-form-POST-JSON-preserved-PDO-ID-string',
            success_case='partial-evidence-' + phase,
            mysql_state='tested-pass', dm_state='tested-pass',
            readback='tested-pass-full-55-column-own-row-and-zero-relations-after-stop',
            parity='partial-evidence-raw-ID-PHP-and-JSON-string-types-match-per-lane-own-sequences-differ',
            cleanup='marked-food-retained-soft-deleted-token-cache-worker-runtime-retired',
            missing_required='not-tested', invalid_type='not-tested', duplicate_retry='not-tested',
            boundary_empty_min_max='partial-evidence-delete-only-is_delete-zero-to-one-no-physical-delete',
            performance='not-tested'))
    return out


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