#!/usr/bin/env python3
"""Ten account HTTP keys, exact historical 39 requests, no credentials persisted."""
import hashlib
import json
import subprocess
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')
BASE = 'work_ai_api/2026-09-30-dm8-interface-acceptance/parallel-owned-store-account-20261012/'
FILES = [
    ('B', 'store', 'owned-account-store-1e42e2328b3b4f7887488c1e5ce5a47a98098887b64cc77fc6dddf4ebe4da104.json'),
    ('B', 'terminal', 'owned-account-terminal-7e2f9876ee7ec7e325800edef0d7d6406eb5a790a01d2242d3febb45e20d5cf4.json'),
    ('C', 'store', 'C_owned_account_store_20932a43.json'),
    ('C', 'terminal', 'C_owned_account_terminal_2f04b4fc.json'),
    ('C', 'store', 'C_owned_account_store_login_shape_e7c9bd9a.json'),
    ('B', 'store', 'owned-account-login-shape-store-d1245068cc5df696149a3a0c47a6000a8c266ff67959e10bc5b0780a72d10e80.json'),
    ('B', 'terminal', 'owned-account-login-shape-terminal-18cfe0296d2071b77a63725045f6aac1549407e6520ad15c5ca1eb135403933b.json'),
    ('C', 'terminal', 'C_owned_account_terminal_login_shape_680d4df6.json'),
]


def verify():
    for name, digest in [
        ('OWNED_STORE_ACCOUNT_MANIFEST_20261012.json', '5e5e5de3f3e4585b1d6d29be358c14748742fb202eb208b70569441b236cdc3c'),
        ('run_owned_store_account_crud_v1_initial.php', '445df048d136d1665eba645f1a29a51df1f3c79126d2a5867885ea3b7c2b87fd'),
        ('run_owned_store_account_crud_v2_login_types.php', '44c637a28720a290d8642dddbc872b704a25bdeb18167727ee20c87a88d0b5f9'),
        ('run_owned_account_login_shape_only.php', '46e3273a70f006d4b1a106c7f0ce7b3d925579aaf5626c23b55ffd65193887f7'),
        ('verify_owned_store_account_receipts.php', '16a0c363cb8a0acbd10bd542620f0cb8e4cf0d7eb39b1840dc1520ec5d707035'),
    ]:
        assert hashlib.sha256((PRIVATE / name).read_bytes()).hexdigest() == digest
    r = json.loads(subprocess.check_output(['/opt/homebrew/opt/php@7.4/bin/php', str(PRIVATE / 'verify_owned_store_account_receipts.php')]))
    assert r['status'] == 'verified' and r['db_or_http_calls'] == 0 and r['true_http_count'] == 39
    assert r['new_unique_keys'] == 10 and len(r['cases']) == 8 and all(r['cross_target_checks'].values())
    assert all(e['passed'] and all(e['checks'].values()) for e in r['cases'].values())
    strong = set()
    total = 0
    for lane, surface, name in FILES:
        events = json.loads((PRIVATE / 'runtime' / name).read_text())['events']
        for e in events:
            if not e['phase'].startswith('after_http_'):
                continue
            total += 1
            action = e['phase'].removeprefix('after_http_')
            path = '/' + surface + '/' + ('Passport/login' if action == 'login' else 'store.User/' + action)
            assert e['path'].split('?')[0] == path
            assert e['method'] == ('GET' if action == 'list' else 'POST')
            if action != 'login':
                assert json.loads(e['raw_response_exact'])['status'] == 200
            elif e['login_response_redacted'].get('data_key_php_types'):
                strong.add((lane, surface))
    assert total == 39 and strong == {('B', 'store'), ('C', 'store'), ('B', 'terminal'), ('C', 'terminal')}


if __name__ == '__main__':
    audit = HERE / 'integration-20261012-batch141.json'
    assert not audit.exists()
    specs = []
    for surface in ['store', 'terminal']:
        for action in ['add', 'edit', 'renew', 'delete', 'login']:
            path = '/' + surface + '/' + ('Passport/login' if action == 'login' else 'store.User/' + action)
            specs.append(item('ai_api', 'POST', path, BASE,
                from_repo='unreviewed', from_source='apifox-2026-05-08',
                risk='owned-non-super-account-only-auth-and-profile-write',
                readback='tested-pass-own-account-role-and-native-login-cache-readback-exact-cleanup',
                success_case='partial-evidence-profile-renew-password-unchanged-not-password-reset' if action == 'renew' else 'partial-evidence-owned-account-positive-lifecycle',
                parity='partial-evidence-native-login-field-types-and-owned-DB-fields-no-secret-wire-storage',
                cleanup='exact-own-accounts-roles-relations-and-both-tokens-zero-external-zero'))
        specs.append(item('ai_api', 'GET', '/' + surface + '/store.User/list', BASE,
                          evidence_only=True, risk='owned-account-filtered-list-regression'))
    tool.main(specs, audit, verify)
