#!/usr/bin/env python3
"""One-time registration of observed formal nutrition FLOAT writes and reads.

Only sealed files are read. Historical source includes the pre-DateMenu fix;
the single explicitly recorded post-run delta is not represented as tested.
"""
import json
from pathlib import Path
import subprocess
import integrate_20261010 as tool
from integrate_20261011_batches40_42 import sha
from integrate_20261011_batches46_48 import item

BASE = tool.STORE + 'parallel-store-nutrition-float-five-write-20261011/'
RUNNER = """import fs from 'node:fs';import path from 'node:path';import assert from 'node:assert/strict';import {pathToFileURL} from 'node:url';const script=process.argv[1],base=path.dirname(script);fs.writeFileSync=(p,data)=>{assert.equal(path.dirname(String(p)),base);assert(fs.existsSync(p));assert(fs.readFileSync(p).equals(Buffer.isBuffer(data)?data:Buffer.from(data)),'sealed derived bytes changed');};await import(pathToFileURL(script).href);"""

def verify():
    root = tool.ROOT / BASE
    for name, pin, counts in [
        ('manifest-original.json', 'e7847c9ffa485daeaa1a60d46e93356ebde901a0492bcd3811920b1bf98071c4', (22,62)),
        ('manifest-final.json', '2cbf76cc5b93960a74f176bc24f575fa7caeba043cfaa9558890dd623b67b6de', (22,48)),
    ]:
        assert sha(root / name) == pin
        manifest = tool.load(BASE + name)
        assert (len(manifest['public']), len(manifest['private'])) == counts
        for kind in ['public','private']:
            for record in manifest[kind]:
                relative = Path(record['file'])
                assert not relative.is_absolute() and '..' not in relative.parts
                path = root / relative
                assert not path.is_symlink() and path.is_file()
                assert path.stat().st_size == record['bytes'] and sha(path) == record['sha256']
                assert format(path.stat().st_mode & 0o777, 'o') == record['mode']
                if kind == 'private':
                    assert record['mode'] == '600'
                    parent = path.parent
                    while parent != root:
                        assert not parent.is_symlink() and parent.stat().st_mode & 0o777 == 0o700
                        parent = parent.parent
    for script, args, assertions in [
        ('verify.mjs',['original'],1800), ('verify-native.mjs',[],640),
        ('verify-candidate.mjs',[],1765), ('verify-native-candidate.mjs',[],715),
        ('verify-cross-phase.mjs',[],264), ('verify-aggregate-resource.mjs',[],88),
    ]:
        result = subprocess.run(['node','--input-type=module','-e',RUNNER,str(root/script),*args],capture_output=True,text=True)
        assert result.returncode == 0, result.stderr
        output = json.loads(result.stdout)
        assert output['assertions'] == assertions, (script, output)
    assert sha(root / 'source-lock-candidate.json') == '881589a34da4ae4d0fc5db36ee5e9e4f75f94e42c0258fc6ae0b9f1cb3185862'
    sources = tool.load(BASE + 'source-lock-candidate.json')
    assert len(sources) == 958
    delta = []
    for relative,digest in sources.items():
        current = sha(tool.ROOT.parent / 'zhctproject/store/application' / relative)
        if current != digest:
            delta.append((relative,digest,current))
    assert delta == [('model/DateMenu.php',
        '61dd192dc186c334346bac06fb50243dc9dceb6315e75b836b2132b7c6173154',
        '56281c991c500b92c7b72660873abf52bdf0e66b7111dfe330f2d6c0ee0a2be4')]
    totals = tool.load(BASE+'manifest-final.json')['totals']
    assert totals['actual_HTTP'] == 72 and totals['native_events'] == 1600
    assert totals['total_DML_attempts'] == 118 and totals['DDL'] == totals['external_writes'] == 0
    assert totals['independent_assertions'] == 5272 and totals['mutation_tests'] == 36

def targets():
    _,rows,_ = tool.read_csv(tool.COVERAGE)
    result = []
    paths = ['/p/nutrition/add','/p/nutrition/update','/m/nutrition/update',
        '/p/nutritionTemplate/add','/p/nutritionTemplate/update',
        '/p/nutrition/info','/m/nutrition/info','/p/nutritionTemplate/info']
    for path in paths:
        controller = 'NutritionTemplate' if 'nutritionTemplate' in path else 'Nutrition'
        target = item('store','POST',path,BASE,
            risk='five-formal-owned-nutrition-writes-plus-info-full-DTO-physical-float32-bits-and-rollback',
            parity='partial-72-real-HTTP-5272-independent-assertions-36-mutations-typed-DTO-declared-generated-data-mapping',
            request_type='actual-JSON-or-form-body-types-preserved-see-plan',
            boundary_empty_min_max='partial-real-half-neighbours-prefix-blank-bool-NULL-missing-positive-overflow-rollback-not-all-inputs',
            cleanup='eleven-marked-rows-per-side-retained-own-worker-cache-auth-cleared-stateless-token-not-global-revoked',
            runtime_inventory_scope='controller-direct-http-observed',
            runtime_observed_method='POST',runtime_direct_http_proof=BASE+'REPORT.md',
            runtime_controller_source=f'application/{path.split("/")[1]}/controller/{controller}.php real App::run POST observed; no camel/underscore alias equivalence inferred')
        matches = [r for r in rows if r['repo'] in ['store','unreviewed'] and tool.norm(r['route_or_command']) == tool.norm(path) and r['method'] in ['POST','*']]
        if not matches:
            target['register_new_runtime_key'] = True
        elif all(r['repo'] == 'unreviewed' for r in matches):
            assert len({r['source'] for r in matches}) == 1
            target.update(from_repo='unreviewed',from_source=matches[0]['source'])
        else:
            assert all(r['repo'] == 'store' for r in matches)
            target['evidence_only'] = True
        result.append(target)
    return result

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