#!/usr/bin/env python3
"""Root one-time integration of twenty real nutrition reports with owned logs."""
import importlib.util
import hashlib
import json
from pathlib import Path
import sys
from unittest.mock import patch
import integrate_20261010 as tool
from integrate_20261011_batches40_42 import run, sha
from integrate_20261011_batches46_48 import item

BASE = tool.STORE + 'parallel-store-nutrition-reports-read24-20261011/remaining20/'
PIN = 'b2ddfba98aaaceaf4818f32a79a498f9584c0537f8297fc9919063f3a51fce25'

def verify():
    root = tool.ROOT / BASE
    assert sha(root / 'manifest20.json') == PIN
    manifest = tool.load(BASE + 'manifest20.json')
    canonical = dict(manifest)
    embedded = canonical.pop('seal_sha256')
    assert embedded == '4342ebe29e7dd6c546774be36cb03b2d875cf7e46c7e4d0130d4020a0084d50e'
    assert hashlib.sha256(json.dumps(canonical, sort_keys=True, separators=(',', ':')).encode()).hexdigest() == embedded
    assert sum(not r['private'] for r in manifest['files']) == 29
    assert sum(r['private'] for r in manifest['files']) == 108
    for record in manifest['files']:
        relative = Path(record['path'])
        assert not relative.is_absolute() and '..' not in relative.parts
        path = root / relative
        assert path.is_file() and not path.is_symlink()
        assert path.stat().st_size == record['bytes'] and sha(path) == record['sha256']
        if record['private']:
            assert relative.parts[0] == 'private' and path.stat().st_mode & 0o777 == 0o600
            parent = path.parent
            while parent != root:
                assert not parent.is_symlink() and parent.stat().st_mode & 0o777 == 0o700
                parent = parent.parent
    spec = importlib.util.spec_from_file_location('nutrition20_verifier', root / 'verify.py')
    verifier = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(verifier)
    original = (root / 'verification20.json').read_text()
    def check_only(path, data, *args, **kwargs):
        assert path == root / 'verification20.json' and data == original
        return len(data)
    with patch.object(Path, 'write_text', check_only):
        verifier.run()  # Validate the exact report bytes without rewriting sealed evidence.
    result = tool.load(BASE + 'verification20.json')
    assert result['HTTP'] == 50 and result['log_rows'] == {'B': 97, 'C': 97}
    assert result['assertions'] == 21320 and result['negative_cases'] == 10
    assert all(len(x) == 20 for x in result['full_DTO'].values())
    assert result['fixture_CAS']['B']['rolled_back_UPDATE'] == 1
    assert result['fixture_CAS']['C']['rolled_back_UPDATE'] == 0
    assert sha(root.parent / 'source-lock.json') == '521f28120d5c576e51330563d1d096e640e5749d1a9bf1d16ffdf9e751e30662'
    sources = json.loads((root.parent / 'source-lock.json').read_text())
    assert len(sources) == 957
    for relative, digest in sources.items():
        assert sha(tool.ROOT.parent / 'zhctproject/store/application' / relative) == digest, relative
    for record in manifest['files']:
        assert sha(root / record['path']) == record['sha256']

def targets():
    plan = tool.load(BASE + 'log-http-plan.json')
    assert len(plan['cases']) == 20
    return [item('store', 'POST', case['path'], BASE,
        risk='formal-owned-nutrition-reports-with-exact-original-controller-log-writes',
        request_type='application/x-www-form-urlencoded-original-post',
        parity='partial-20-complete-BC-body-byte-identical-pairs-21320-assertions-10-mutations',
        boundary_empty_min_max='partial-complete-nonzero-owned-meals-recipe-fixture-zero-DECIMAL-branch-still-open',
        cleanup='marked-eight-fixture-and-97-logs-each-retained-own-worker-cache-request-cleaned-not-global-token-revoke')
        for case in plan['cases']]

if __name__ == '__main__':
    audit = Path(__file__).with_name('integration-20261011-batch70.json')
    assert not audit.exists(), 'Preserve original transition audit'
    tool.main(targets(), audit, verify)
