#!/usr/bin/env python3
"""Integrate original assessment writes and cached-only meal suggestion reads."""
import hashlib
import json
import subprocess
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item
from integrate_20261012_batch148 import shape

HERE = Path(__file__).resolve().parent
PRIVATE = Path('/private/tmp/cdx-ai-hk-course-b.Kmdirn')
BASE = 'work_ai_api/2026-09-30-dm8-interface-acceptance/parallel-assessment-suggestion-20261012/'


def verify():
    manifest_path = PRIVATE / 'meal161-safe/MANIFEST_161.json'
    assert hashlib.sha256(manifest_path.read_bytes()).hexdigest() == '84aa368384efc946334e2c458f5321a28a548b68b0af0e805b84bac5057357a0'
    manifest = json.loads(manifest_path.read_text())
    assert len(manifest['assets_sha256']) == 32
    for name, digest in manifest['assets_sha256'].items():
        assert not Path(name).is_absolute() and '..' not in Path(name).parts
        assert hashlib.sha256((PRIVATE / name).read_bytes()).hexdigest() == digest
    result = json.loads(subprocess.check_output(['/opt/homebrew/opt/php@7.4/bin/php',
        str(PRIVATE / 'meal161-safe/verify_meal161_abc.php')]))
    assert result['status'] == 'verified_161_two_new_keys_owned_B_C'
    assert result['business_http_actual'] == {'B': 4, 'C': 2, 'total': 6, 'B_tool_auth_false_red': 2}
    assert result['setup_dml'] == {'B': 2, 'C': 2} and result['real_coze_qw_queue_calls'] == 0
    for case in result['cases'].values():
        assert len(case['assess_food_ids']) == 4 and case['row_transitions_checked'] and case['token_absent']
    pairs = [
        ('runtime/meal161-recommend-add-6d5d402c5f5b6206a0ec8d52ea9828c34f3b871e75e85993c9ea9548f284a63e.json',
         'meal161-safe/C_meal161_recommend_add.json'),
        ('runtime/meal161-suggestion-get-v3-c48b55ea0ef6f16f5602d542a946796339e80852029ad4204249880b3cdb0275.json',
         'meal161-safe/C_suggestion_get_v3.json'),
    ]
    for pair in pairs:
        bodies = []
        for name in pair:
            events = {event['phase']: event for event in json.loads((PRIVATE / name).read_text())['events']}
            body = json.loads(events['after_http']['raw_response_exact'])
            assert type(body['status']) is int and body['status'] == 200
            body.pop('trace_id', None)
            bodies.append(body)
        assert bodies[0] == bodies[1] and shape(bodies[0]) == shape(bodies[1])


if __name__ == '__main__':
    audit = HERE / 'integration-20261012-batch161.json'
    assert not audit.exists()
    specs = [
        item('ai_api', 'POST', '/terminal/recommend.Recommend/add', BASE,
            risk='owned-assessment-master-and-four-food-rows-real-disabled-operator-private-auth',
            success_case='partial-evidence-first-assessment-reserve-and-score-types6-7-8-no-repeat-update',
            readback='tested-pass-own-master1-food4-linked-real-operator-other-own-rows-natural-dish-unchanged',
            cleanup='own-master-food-and-disabled-operator-retained-private-token-zero-no-real-queue'),
        item('ai_api', 'GET', '/api/meal.Meal/suggestion', BASE,
            risk='prepared-own-fresh-suggestion-cache-read-Coze-constructor-hard-denied',
            success_case='partial-evidence-fresh-cached-suggestion-only-not-Coze-generation',
            readback='tested-pass-four-return-fields-from-own-cache-and-five-source-rowsets-unchanged',
            boundary_empty_min_max='partial-evidence-Chinese-multiline-and-interior-empty-line-preserved',
            cleanup='own-cache-row-retained-private-token-zero-prior-two-auth-fixture-failures-kept'),
    ]
    tool.main(specs, audit, verify)
