"""Publish source-bound recorded labs; never execute a numerical example."""
from pathlib import Path
import hashlib, html, json, re, shutil

GUIDES = ['native-wall-force-sequence', 'column-wall-friction', 'column-no-slip',
          'column-poiseuille', 'static-obstacle-geometry', 'static-obstacle-flow', 'requirements-roadmap', 'material-preview-contracts', 'cpu-scheduling-contracts', 'cad-visualization-contracts']

def metadata(repo):
    repo = Path(repo)
    data = json.loads((repo/'docs/education/native-sequence.json').read_text())
    if data.get('schema') != 'rheon-native-sequence-source-v2':
        raise ValueError('Unsupported proof metadata schema; current status required')
    if data.get('schema') == 'rheon-native-sequence-source-v2':
        current = data.get('current_reviewed_proof')
        if not isinstance(current, dict):
            raise ValueError('Missing current reviewed proof status')
        for key in ('public_theorems',
                    'explicit_expected_declarations', 'audited_declarations', 'lean_ci'):
            if key not in current or current[key] != data.get(key):
                raise ValueError('Current reviewed proof metadata mismatch: '+key)
        if current.get('status') == 'reviewed-pending-kernel-qualification':
            if any(current.get(key) is not None for key in
                   ('audited_declarations', 'lean_ci', 'local_qualification')) or data.get('local_kernel_receipt_sha256') is not None:
                raise ValueError('Pending proof status cannot carry qualification evidence')
        elif current.get('status') == 'passed':
            if (type(current['audited_declarations']) is not int or
                    current['audited_declarations'] < current['explicit_expected_declarations'] or
                    not (current.get('lean_ci') or current.get('local_qualification'))):
                raise ValueError('Passed proof status requires explicit qualification evidence')
        else:
            raise ValueError('Unknown current reviewed proof status')
    return data

def validate_labs(data, directory):
    if directory is None:
        return
    directory = Path(directory)
    for lab in data['labs']:
        root = directory/lab['id']
        if any(not p.is_file() or p.is_symlink() for p in root.iterdir()):
            raise ValueError('Recorded lab packet must contain only declared regular files: '+lab['id'])
        actual = {p.name: hashlib.sha256(p.read_bytes()).hexdigest()
                  for p in root.iterdir() if p.is_file()}
        if actual != lab['files']:
            raise ValueError('Recorded lab bytes differ from accepted packet: '+lab['id'])

def publish(data, output, directory=None):
    output = Path(output)
    cards = []
    for i, lab in enumerate(data['labs'], 1):
        key = lab['id']
        if directory is not None:
            dest = output/'native-labs'/key
            shutil.copytree(Path(directory)/key, dest)
            if key == 'wall-friction':
                # Original HTML/CSV is preserved at input. This derived banner
                # states that case links show saved profiles, not live parameters.
                for p in dest.glob('*.html'):
                    text = p.read_text()
                    note = '<p role="note" class="snapshot-note"><strong>Snapshot playback.</strong> These pages display six fixed native runs. Case links select recorded results; they do not recompute parameters or run a live simulation. CSVs retain four actual saved times. The plot displays the final saved profile, not a general liquid solver.</p>'
                    text = re.sub(r'(<h1>.*?</h1>)', lambda m: m[0]+note, text, count=1)
                    text = text.replace('<meta charset=utf-8>', '<meta charset=utf-8><meta name="viewport" content="width=device-width,initial-scale=1"><style>body{font:16px system-ui;max-width:900px;margin:24px auto;padding:0 16px}svg{width:100%;height:auto}table{width:100%;font-size:.85rem;table-layout:fixed;overflow-wrap:anywhere}td,th{padding:5px!important}.snapshot-note{padding:12px;background:#eff7fa;line-height:1.5}</style>')
                    p.write_text(text)
            action = f'<a href="native-labs/{key}/index.html">Open recorded native lab →</a>'
        else:
            action = '<p>Recorded bundle is not included in this source-only build. No simulation was run to create a substitute.</p>'
        guide = {'wall-friction':'column-wall-friction', 'no-slip':'column-no-slip', 'poiseuille':'column-poiseuille'}[key]
        cards.append(f'<article><h2>{i} · {html.escape(key)}</h2><p>{html.escape(lab["model"])}</p><p>{lab["counts"]["cases"]} fixed cases; {lab["counts"]["saved_times"]} saved times.</p><p>Reference: {html.escape(lab["reference"])}</p>{action}<p><a href="implementation/{guide}.html">Equation, units and proof assumptions →</a></p></article>')
    (output/'native-sequence.json').write_text(json.dumps(data, indent=2)+'\n')
    receipt = {'schema':'rheon-native-presentation-v1', 'numerical_calls':0,
               'recorded_bundles_included':directory is not None,
               'accepted_inputs':data['labs'],
               'files':{str(p.relative_to(output)):hashlib.sha256(p.read_bytes()).hexdigest()
                        for p in sorted((output/'native-labs').rglob('*')) if p.is_file()}}
    (output/'native-presentation.json').write_text(json.dumps(receipt, indent=2)+'\n')
    return '<p class="eyebrow">THREE NATIVE STEPS / ONE FIXED SLAB</p><h1>Wall traction, exact trace, external force.</h1><p class="lede">Follow the same liquid dual mass and endpoint basis through finite Navier traction, compatible no-slip constraints, then uniform tangential forcing.</p><p role="note"><strong>Snapshot playback.</strong> Native controls select recorded cases and saved times. They do not provide live parameter recomputation or a general liquid solver. The original six 3D reference labs are separate analytical/stored mechanisms.</p><p><a href="implementation/native-wall-force-sequence.html">Read the progression</a> · <a href="implementation/requirements-roadmap.html">Remaining requirements and next geometry contract</a></p><div class="cards">'+''.join(cards)+'</div>'
