"""Finish v5 acceptance without changing frozen models, predictions or the archive.

An inherited remote DISPLAY blocks this host's headless browser/compositor.
Unset DISPLAY for the verifier, without changing its browser launch flags or assertions.
Keep the original failure and publish acceptance evidence as a separate ZIP.
"""
from __future__ import annotations

import json
import os
from pathlib import Path
import runpy
import sys
from zipfile import ZIP_DEFLATED, ZipFile

PROJECT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(PROJECT))
sys.path.insert(0, '/tmp/opencode/pallet_review_pw132')
os.environ.setdefault('PLAYWRIGHT_NODEJS_PATH', '/tmp/opencode/pallet_review_browser_tools/node')

from pallet.cluster_targets import digest
from pallet.pose_dataset import write_json
from pallet.pose_paper_data import ROOT
from pallet.pose_paper_results import audit
from pallet.pose_refinement import atomic_json, now


def main():
    status = json.loads((ROOT / 'run_status.json').read_text())
    if status['state'] == 'failed':
        write_json(ROOT / 'original_browser_failure.json', status)
    verifier = PROJECT / 'scripts/verify_pose_paper_html_v5.py'
    module = runpy.run_path(str(verifier), run_name='_pose_paper_original_verifier')
    print('Running unchanged packaged verifier without inherited remote DISPLAY', flush=True)
    display = os.environ.pop('DISPLAY', None)
    try:
        module['main'](ROOT)
    finally:
        if display is not None:
            os.environ['DISPLAY'] = display
    write_json(ROOT / 'browser_recovery.json', dict(
        completed_at=now(), verifier_sha256=digest(verifier),
        recovery_script_sha256=digest(Path(__file__)),
        inherited_remote_DISPLAY_present=display is not None,
        verifier_environment_change='unset_DISPLAY_for_headless_subprocess_only',
        browser_launch_flags_changed=False,
        verifier_assertions_changed=False, models_and_predictions_changed=False,
        archive_changed=False, prior_failure_preserved='original_browser_failure.json'))
    audit()
    files = [ROOT / name for name in (
        'final_acceptance.json', 'browser_recovery.json', 'original_browser_failure.json',
        'gpu_inference_validation.json', 'independent_protection_validation.json',
        'delivery_manifest.json', 'CONCLUSIONS_zh.md')]
    files += sorted((ROOT / 'report_validation').glob('*'))
    members = {str(p.relative_to(ROOT)): p for p in files if p.is_file()}
    members['source/scripts/finish_pose_paper_benchmark_v5.py'] = Path(__file__)
    archive = ROOT / 'pallet_pose_paper_validation_v5.zip'
    if not archive.exists():
        with ZipFile(archive, 'x', compression=ZIP_DEFLATED) as z:
            for name, path in sorted(members.items()):
                z.write(path, name)
    else:
        import hashlib
        with ZipFile(archive) as z:
            if set(z.namelist()) != set(members):
                raise ValueError('Existing evidence archive has different members')
            for name, path in members.items():
                if hashlib.sha256(z.read(name)).hexdigest() != digest(path):
                    raise ValueError('Refusing to replace an earlier evidence archive')
    write_json(ROOT / 'validation_delivery_manifest.json', dict(
        archive=archive.name, sha256=digest(archive), bytes=archive.stat().st_size,
        members={name: digest(path) for name, path in sorted(members.items())}))
    atomic_json(ROOT / 'run_status.json', dict(
        state='completed', completed_at=now(),
        original_failure_preserved='original_browser_failure.json',
        final_acceptance_sha256=digest(ROOT / 'final_acceptance.json'),
        completion_entrypoint='scripts/finish_pose_paper_benchmark_v5.py',
        robot_command_eligible=False))
    print(json.dumps(dict(state='completed', archive=str(archive))), flush=True)


if __name__ == '__main__':
    main()
