#!/usr/bin/env python3
"""Root-only integration of the sealed AI customer-read batch and fixes."""
import hashlib
import json
from pathlib import Path
import subprocess
import sys

import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item

AI_REPO = tool.ROOT.parent / 'zhctproject/ai_api'
PRIVATE = Path('/Users/wiscourper/Documents/workspace/local')
FAST = PRIVATE / 'dm8-ai-fast5-evidence-20261011.OoE131'
RANK = PRIVATE / 'dm8-ai-rank-current-fix-20261011.XgFKBX'
SIGN = PRIVATE / 'dm8-ai-sign-detail-fixed-read-20261011.daSosT'
SUMMARY = tool.ROOT / 'work_ai_api/2026-09-30-dm8-interface-acceptance/parallel-ai-customer-fast5-read-20261011/ROOT_REVIEW_RANK_SIGN_20261011.md'


def verify_seal(directory, expected):
    result = json.loads(subprocess.run(
        [sys.executable, '-B', str(directory / 'verify_seal.py')],
        check=True, capture_output=True, text=True).stdout)
    assert result['passed']
    for key, value in expected.items():
        assert result[key] == value, (directory, key, result[key])


def verify():
    assert SUMMARY.is_file()
    verify_seal(FAST, {'assets': 255, 'seal_checks': 788, 'audit_checks': 14928})
    verify_seal(RANK, {'assets': 85, 'seal_checks': 268, 'audit_checks': 6563})
    verify_seal(SIGN, {'assets': 129, 'seal_checks': 402, 'audit_checks': 12758})
    assert subprocess.run(['git', '-C', str(AI_REPO), 'rev-parse', 'HEAD'],
        check=True, capture_output=True, text=True).stdout.strip().startswith('72cf948d')
    service = AI_REPO / 'app/api/service/Yingjiduo.php'
    assert hashlib.sha256(service.read_bytes()).hexdigest() == 'c13de9188aa1900a020e206fed1f07ea1e26d202e72255d2def805fb96282e59'
    sign_service = AI_REPO / 'app/api/service/Sign.php'
    assert 'toArray()' in sign_service.read_text()
    rank_report = (RANK / 'REPORT.md').read_text()
    fast_report = (FAST / 'REPORT.md').read_text()
    sign_report = (SIGN / 'REPORT.md').read_text()
    assert 'Rank.current' in rank_report and 'rankNo2' in rank_report
    assert 'Rank/current' in fast_report and 'Rank/byDate' in fast_report
    assert 'published id1' in fast_report and '唯一新GET' in sign_report
    assert '无安全published活动' in sign_report and '0Auth/0HTTP' in sign_report


def targets():
    base = 'work_ai_api/2026-09-30-dm8-interface-acceptance/parallel-ai-customer-fast5-read-20261011/'
    out = []
    for path, note in [
        ('/api/yingjiduo.Rank/current', 'two-engine-current-rank-one-period-sort-and-data-snapshot'),
        ('/api/yingjiduo.Rank/byDate', 'two-engine-single-date-single-record-only'),
    ]:
        out.append(item('ai_api', 'GET', path, base,
            evidence=base + 'ROOT_REVIEW_RANK_SIGN_20261011.md',
            from_source='controller-action-source',
            terminal='current-customer-API', role='existing-marked-readonly-actor',
            risk='scoped-health-ranking-read',
            scope='secondary-own-activity-source-and-original-group-count-meaning',
            success_case='partial-evidence-one-real-get-per-engine-and-one-sampled-parameter-set-' + note,
            mysql_state='tested-pass',
            dm_state='tested-pass',
            readback='tested-pass-scoped-native-source-projection',
            parity='partial-evidence-response-shape-and-types-preserved-independent-business-source-values-not-forced-equal',
            cleanup='readonly-source-unchanged-token-worker-cache-released-private-seal-preserved'))
    for path, note in [
        ('/api/yingjiduo.Sports/record', 'records'),
        ('/api/yingjiduo.Sports/total', 'totals'),
    ]:
        out.append(item('ai_api', 'GET', path, base,
            evidence=base + 'ROOT_REVIEW_RANK_SIGN_20261011.md',
            from_source='controller-action-source',
            terminal='current-customer-API', role='existing-marked-readonly-actor',
            risk='scoped-health-read-empty-only',
            scope='secondary-own-sports-source-' + note,
            success_case='limited-empty-only-both-sources-have-no-own-nonempty-sports-' + note,
            mysql_state='tested-pass-empty-only', dm_state='tested-pass-empty-only',
            readback='limited-empty-only-no-nonempty-own-source',
            parity='limited-empty-response-only-no-nonempty-DTO-or-cross-snapshot-value-claim',
            cleanup='readonly-source-unchanged-token-worker-cache-released-private-seal-preserved'))
    out.append(item('ai_api', 'GET', '/api/Sign/detail', base,
        evidence=base + 'ROOT_REVIEW_RANK_SIGN_20261011.md',
        from_source='controller-action-source',
        terminal='current-customer-API', role='existing-marked-readonly-actor',
        risk='sign-detail-and-referenced-image-metadata-read',
        scope='existing-published-sign-detail-and-exact-image-row-only',
        success_case='limited-only-MySQL-has-safe-existing-published-sample-DM-no-sample',
        mysql_state='tested-pass-nonempty-owned-source', dm_state='not-tested-no-safe-published-row',
        readback='limited-MySQL-nonempty-DM-no-safe-source',
        parity='limited-MySQL-fixed-Collection-read-only-DM-not-requested',
        cleanup='readonly-source-unchanged-MySQL-token-worker-cache-released-DM-no-token-or-worker-private-seal-preserved'))
    return out


if __name__ == '__main__':
    audit = Path(__file__).with_name('integration-20261011-batch92.json')
    assert not audit.exists(), 'Preserve any previous integration evidence'
    tool.main(targets(), audit, verify)
