#!/usr/bin/env python3
"""Rebuild the frozen pre-numeric research worker without replacing the current CLI."""
from pathlib import Path
import shutil
import subprocess
import sys
import tarfile

ROOT = Path(__file__).resolve().parents[3]
FOLDER = Path(__file__).resolve().parent
PROJECT = ROOT / 'target/numeric-frozen-replay'
PROJECT.mkdir(parents=True, exist_ok=True)
with tarfile.open(FOLDER / 'baseline_source.tar.gz') as archive:
    for entry in archive:
        if not (PROJECT / entry.name).resolve().is_relative_to(PROJECT.resolve()):
            raise ValueError('Invalid frozen source path')
        archive.extract(entry, PROJECT)
(PROJECT / 'examples').mkdir(exist_ok=True)
shutil.copy2(FOLDER / 'worker.rs', PROJECT / 'examples/numeric_density.rs')
subprocess.run([sys.executable, str(FOLDER / 'prepare.py')], cwd=ROOT, check=True)
subprocess.run(['cargo', 'build', '--offline', '--locked', '--release', '--jobs', '2',
                '--manifest-path', str(PROJECT / 'Cargo.toml'), '--target-dir', str(ROOT / 'target'),
                '--example', 'numeric_density'], cwd=ROOT, check=True)
with (PROJECT / 'research_results.json').open('w') as output, (PROJECT / 'research_run.log').open('w') as log:
    subprocess.run([str(ROOT / 'target/release/examples/numeric_density')], cwd=ROOT, stdout=output, stderr=log, check=True)
print(f'Frozen baseline replay written to {PROJECT / "research_results.json"}; reviewed evidence is preserved.')
