"""Reproduce the wiki's native mCherry example from a CERNAL source checkout.

Download this script and mcherry.fasta into the same directory. From a checkout of
cernal_software at 9a5ca657fa637614c13a092b2046cb5ab9a87812, with its dependencies
installed (Python 3.13 and ViennaRNA 2.7.2 for the recorded run), execute:

PYTHONDONTWRITEBYTECODE=1 PYTHONPATH=src .venv/bin/python /path/to/reproduce.py /tmp/mcherry-repeat

The destination must not already exist. No application database or server is used.
Numerical fields should be compared at an appropriate tolerance; audit timestamps
and destination paths naturally differ between runs. Do not bypass export holds.
"""
from dataclasses import asdict
from pathlib import Path
import hashlib
import json
import sys

from engine.client import LocalEngine
from engine.contract import JobRequest


def main():
    if len(sys.argv) != 2:
        raise SystemExit("Usage: reproduce.py NEW_OUTPUT_DIRECTORY")
    output = Path(sys.argv[1]).resolve()
    output.mkdir(parents=True, exist_ok=False)
    fasta = Path(__file__).with_name("mcherry.fasta")
    sequence = "".join(
        line.strip() for line in fasta.read_text().splitlines()
        if line.strip() and not line.startswith(">")
    ).upper().replace("T", "U")
    expected_hash = "9cb1f52635692b9413242a227afbf36a896a11e2b99ad48660e864998d00c9c9"
    if hashlib.sha256(sequence.encode()).hexdigest() != expected_hash:
        raise SystemExit("Input sequence does not match the recorded 711 nt mCherry example.")
    request = JobRequest(
        schema_version="1",
        run_id="wiki-mcherry-2026-10-07",
        idempotency_key="wiki-mcherry-2026-10-07",
        input_mode="direct",
        input_path="",
        input_checksum="",
        trigger_sequence=sequence,
        organism="ecoli",
        params={},
        gate_families=["toehold"],
        scoring_profile="default",
        seed=7,
        output_dir=str(output / "artifacts"),
    )
    result = LocalEngine().run(request, lambda percent, stage: True)
    (output / "request.json").write_text(json.dumps(asdict(request), indent=2) + "\n")
    (output / "result.json").write_text(json.dumps(asdict(result), indent=2) + "\n")
    print(f"Status: {result.status}; ranked: {len(result.accepted)}; scored rejections: {len(result.rejected)}")
    print(f"Artifacts: {', '.join(sorted(set(a.kind for a in result.artifacts)))}")
    if result.error:
        print(result.error)
        raise SystemExit(1)


if __name__ == "__main__":
    main()
