"""将固定场景装配到新的输出目录；不运行 Runtime、Docker 或模型。"""

from __future__ import annotations

import argparse
import hashlib
import json
import shutil
import subprocess
import sys
from pathlib import Path

SOURCE = Path(__file__).resolve().parent
HARNESS = SOURCE.parents[3]
GROUPS = ("a3", "a4", "a5")


def sha(file: Path) -> str:
    return hashlib.sha256(file.read_bytes()).hexdigest()


def main() -> int:
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--cli-root", type=Path, required=True)
    parser.add_argument("--output", type=Path, required=True)
    options = parser.parse_args()
    cli_root = options.cli_root.resolve()
    output = options.output.resolve()
    if output.exists() or output.is_relative_to(SOURCE):
        parser.error(
            "Output must be a new directory outside the fixture source; existing files are never replaced"
        )
    if (
        not (cli_root / "bin/comet.js").is_file()
        or not (cli_root / "dist/app/cli/index.js").is_file()
    ):
        parser.error("Provide a built public CLI root containing bin, dist and assets")
    if not (HARNESS / "eval/pyproject.toml").is_file():
        parser.error("The repository Eval harness is unavailable")

    output.mkdir(parents=True)
    for group in GROUPS:
        target = output / group
        target.mkdir()
        (target / ".generated-fixture").write_text(
            "Generated by prepare.py; immutable model inputs\n", encoding="utf-8"
        )
        for workflow in ("native", "classic"):
            shutil.copytree(SOURCE / group / workflow, target / workflow)
            (target / f"{workflow}-owner").mkdir()
        for file in (SOURCE / group).glob("*.py"):
            shutil.copyfile(file, target / file.name)
        shutil.copyfile(SOURCE / "common/agent_call_audit.py", target / "agent_call_audit.py")
        shutil.copyfile(SOURCE / "run.py", target / "run.py")

    candidate = {
        file.relative_to(cli_root).as_posix(): sha(file)
        for folder in ("bin", "dist", "assets")
        for file in sorted((cli_root / folder).rglob("*"))
        if file.is_file()
    }
    candidate["package.json"] = sha(cli_root / "package.json")
    for group in GROUPS:
        command = [sys.executable, str(output / group / "assemble.py"), "--cli-root", str(cli_root)]
        if group != "a5":
            command.extend(["--harness-root", str(HARNESS)])
        result = subprocess.run(command, cwd=HARNESS / "eval", check=False)
        if result.returncode:
            return result.returncode
        manifest_path = output / group / "assembly-inputs.json"
        manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
        manifest["candidateFiles"] = candidate
        manifest["candidateHash"] = hashlib.sha256(
            json.dumps(candidate, sort_keys=True).encode()
        ).hexdigest()
        manifest_path.write_text(json.dumps(manifest, indent=2), encoding="utf-8")

    sources = {
        file.relative_to(SOURCE).as_posix(): sha(file)
        for file in sorted(SOURCE.rglob("*"))
        if file.is_file() and "__pycache__" not in file.parts
    }
    record = {
        "schema": "comet.eval.edit-continuation-fixtures.v1",
        "cliRoot": str(cli_root),
        "harnessRoot": str(HARNESS),
        "sourceRoot": str(SOURCE),
        "sourceFiles": sources,
        "groups": list(GROUPS),
        "modelStarted": False,
        "scope": "Assembly only; no Runtime, Docker, checks, user decisions or model execution",
    }
    (output / "prepared.json").write_text(json.dumps(record, indent=2), encoding="utf-8")
    print(json.dumps({"prepared": str(output), "groups": list(GROUPS), "modelStarted": False}))
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
