#!/usr/bin/env python3
"""Root intake: three nonempty export keys and three explicitly empty branches."""
import hashlib
import json
import subprocess
import sys
from pathlib import Path
import integrate_20261010 as tool
from integrate_20261011_batches46_48 import item
from integrate_20261013_batches221_223_224_226 import shape

HERE = Path(__file__).resolve().parent
ROOT = Path('/Users/wiscourper/Documents/workspace/local/dm8-independent-20261013/session-export')
REPORT = tool.AI + 'parallel-s3-order-export-20261013/ROOT_REVIEW.md'
AI_COMMIT = '9a0ff1b3e6a36105838cf75232c7f618fe185ee8'
STORE_COMMIT = '831d498422d8e4e49fd1c4733f359714329f6e92'
STORE_CASES = {365: ('POST', '/p/supplementmealorder/export'),
               366: ('POST', '/p/cashoutorder/export'),
               370: ('GET', '/p/cashrefund/export'), 371: ('POST', '/p/cashrefund/export')}


def pin(file, expected):
    assert hashlib.sha256(file.read_bytes()).hexdigest() == expected, file.name


def reflections(boundary, repo, commit):
    for name, entry in boundary['reflection'].items():
        path = name.replace('\\', '/') + '.php'
        if repo == 'store':
            assert path.startswith('app/')
            path = 'application/' + path[4:]
        raw = subprocess.check_output(['git', '-C', str(tool.source_root(repo)), 'show', commit + ':' + path])
        assert hashlib.sha256(raw).hexdigest() == entry['sha'], name


def verify():
    pin(ROOT / 'FINAL_MANIFEST.json', '0ed4cdb2327c0a54963cbada2a6c3686cd3cc1eb634c7fec9318eb39536696d7')
    pin(ROOT / 'verify_all_offline.py', 'b1853b1bb8e1f95fd1238e418e64c5e6002cf127ad135cc3190b49128810a4e1')
    result = json.loads(subprocess.check_output([sys.executable, '-B', str(ROOT / 'verify_all_offline.py')]))
    assert result['verified'] and len(result['checks']) == 8 and result['database_HTTP_calls'] == 0
    for lane in ('B', 'C'):
        for batch, (method, path) in STORE_CASES.items():
            side = ROOT / ('batch' + str(batch)) / lane
            intent = json.loads((side / 'server-request-intent.json').read_text())
            assert intent['method'] == method and intent['path'] == path and intent['attempt'] == 1
            raw = json.loads((side / 'response.raw').read_text())
            receipt = json.loads((side / 'result.json').read_text())
            assert raw == receipt['json'] and shape(raw) == shape(receipt['json'])
            pin(side / 'final.xlsx', receipt['file_sha'])
            reflections(json.loads((side / 'http-boundary.json').read_text()), 'store', STORE_COMMIT)
        side = ROOT / 'batch369' / lane
        reflections(json.loads((side / 'boundary.json').read_text()), 'ai_api', AI_COMMIT)
        for module in ('store', 'terminal'):
            intent = json.loads((side / (module + '-server-intent.json')).read_text())
            assert intent['method'] == 'POST' and intent['path'] == '/' + module + '/order.export/exportOrder'
            raw_bytes = (side / (module + '-response.raw')).read_bytes()
            raw = json.loads(raw_bytes)
            receipt = json.loads((side / (module + '-result.json')).read_text())
            server = json.loads((side / (module + '-server-result.json')).read_text())
            assert raw == receipt['json'] and shape(raw) == shape(receipt['json'])
            assert hashlib.sha256(raw_bytes).hexdigest() == server['raw_sha'] and server['writes'] == 1
            pin(side / (module + '-http.xlsx'), server['file_sha'])
    subprocess.check_call(['git', '-C', str(tool.source_root('ai_api')), 'merge-base', '--is-ancestor', AI_COMMIT, 'develop_dameng'])


if __name__ == '__main__':
    audit = HERE / 'integration-20261013-s3-exports.json'
    assert not audit.exists(), 'Never replay integration main'
    rows = []
    for batch, (method, path) in STORE_CASES.items():
        empty = batch != 365
        row = item('store', method, path, '', evidence=REPORT,
            request_type='GET-query' if method == 'GET' else 'application/x-www-form-urlencoded',
            success_case='partial-evidence-empty-file-real-export-task' if empty else 'partial-evidence-nonempty-original-HTTP-job-consumer-XLSX',
            readback='tested-pass-own-export-task-persisted-source-unchanged-independent-XLSX-values-types',
            parity='partial-evidence-complete-JSON-and-file-cell-contract-transaction-isolation-not-real-queue',
            cleanup='new-completed-marked-export-records-retained-no-business-source-mutation-no-real-OSS')
        if empty:
            row.update(mysql_state='partial-evidence-empty-export-source-real-task-persisted',
                       dm_state='partial-evidence-empty-export-source-real-task-persisted')
        rows.append(row)
    rows += [item('ai_api', 'POST', '/' + module + '/order.export/exportOrder', '', evidence=REPORT,
        role='original-controller-auth-with-disclosed-synthetic-login-principal-not-password-login',
        request_type='application/x-www-form-urlencoded',
        success_case='partial-evidence-nonempty-eight-column-HTTP-and-full28-readonly-regression',
        readback='tested-pass-own-completed-export-record-and-source-five-tables-unchanged-XLSX-all-cell-types-values',
        parity='partial-evidence-original-HTTP-and-money-two-decimal-file-parity-old-reds-retained',
        cleanup='completed-marked-export-records-retained-source-rows-unchanged-no-real-OSS-or-payments')
        for module in ('store', 'terminal')]
    tool.main(rows, audit, verify)
