"""Evaluate a registered checkpoint with its hash-verified source snapshot."""
from __future__ import annotations

import argparse
import hashlib
import json
from pathlib import Path, PurePosixPath
import subprocess
import sys
import tarfile

from pallet.data.protocol import file_digest, write_json


def restore_source(run, output_root="outputs/replayed_sources"):
    archive = Path(run["source_snapshot"])
    identity = run["source_snapshot_id"]
    manifest = json.loads(archive.with_suffix("").with_suffix(".json").read_text())
    actual_identity = hashlib.sha256(json.dumps(manifest, sort_keys=True).encode()).hexdigest()
    if identity != actual_identity:
        raise ValueError("source snapshot manifest differs from registered identity")
    destination = Path(output_root).resolve() / identity
    with tarfile.open(archive, "r:gz") as source:
        members = source.getmembers()
        names = [member.name for member in members]
        if len(names) != len(set(names)) or set(names) != set(manifest):
            raise ValueError("source archive members differ from snapshot manifest")
        for member in members:
            name = PurePosixPath(member.name)
            if (not member.isfile() or name.is_absolute() or ".." in name.parts
                    or not name.parts):
                raise ValueError("source archive contains unsafe or non-file entry")
            stream = source.extractfile(member)
            if stream is None:
                raise ValueError("source snapshot member has no payload")
            payload = stream.read()
            if hashlib.sha256(payload).hexdigest() != manifest[member.name]:
                raise ValueError(f"source archive payload changed: {member.name}")
            target = destination.joinpath(*name.parts)
            if target.is_symlink() or any(parent.is_symlink() for parent in target.parents):
                raise ValueError("replayed source path traverses a symlink")
            if target.exists():
                if file_digest(target) != manifest[member.name]:
                    raise ValueError(f"existing replayed source differs: {member.name}")
            else:
                target.parent.mkdir(parents=True, exist_ok=True)
                target.write_bytes(payload)
    return destination


def replay(checkpoint, annotations, subset, output, *, cache_index,
           device, split="val", reference_annotations=None, bootstrap_samples=0):
    checkpoint = Path(checkpoint).resolve()
    output = Path(output).resolve()
    run = json.loads((checkpoint.parent / "run.json").read_text())
    if output.exists() or output.with_suffix(".replay.json").exists():
        raise ValueError("evaluation output already exists; select a new versioned path")
    source = restore_source(run)
    args = [sys.executable, "-m", "pallet.cli", "evaluate",
            "--root", run["root"], "--protocol", run["protocol"],
            "--annotations", str(Path(annotations).resolve()),
            "--checkpoint", str(checkpoint), "--output", str(output),
            "--cache-index", str(Path(cache_index).resolve()),
            "--split", split, "--device", device,
            "--bootstrap-samples", str(bootstrap_samples)]
    if subset:
        args.extend(("--subset", str(Path(subset).resolve())))
    if reference_annotations:
        args.extend(("--reference-annotations", str(Path(reference_annotations).resolve())))
    output.parent.mkdir(parents=True, exist_ok=True)
    log = output.with_suffix(".replay.log")
    with log.open("w", encoding="utf-8") as stream:
        result = subprocess.run(args, cwd=source, stdout=stream, stderr=subprocess.STDOUT,
                                check=False)
    if result.returncode:
        raise RuntimeError(f"archived evaluation failed with exit {result.returncode}; see {log}")
    values = json.loads(output.read_text())
    metadata = {"source_snapshot_id": run["source_snapshot_id"],
                "source_directory": str(source), "registered_code_sha256": run["code_sha256"],
                "checkpoint_sha256": file_digest(checkpoint),
                "annotations_sha256": file_digest(annotations),
                "evaluation_sha256": file_digest(output),
                "split": split, "command": args,
                "note": "Archived project source replay; installed dependency versions are those in the current locked environment."}
    write_json(output.with_suffix(".replay.json"), metadata)
    return {"output": str(output), "source_snapshot_id": run["source_snapshot_id"],
            "images": values["images"], "AP50": values["AP50"],
            "AP75": values["AP75"], "AP50_95": values["AP50_95"]}


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("--checkpoint", required=True)
    parser.add_argument("--annotations", required=True)
    parser.add_argument("--subset")
    parser.add_argument("--output", required=True)
    parser.add_argument("--cache-index", default="outputs/cache_v5/sealed_index.json")
    parser.add_argument("--device", required=True)
    parser.add_argument("--split", choices=("val", "test"), default="val")
    parser.add_argument("--reference-annotations")
    parser.add_argument("--bootstrap-samples", type=int, default=0)
    args = parser.parse_args()
    print(json.dumps(replay(args.checkpoint, args.annotations, args.subset, args.output,
                            cache_index=args.cache_index, device=args.device,
                            split=args.split, reference_annotations=args.reference_annotations,
                            bootstrap_samples=args.bootstrap_samples)))
