"""Run the same source-backed recipes through all three clients on Linux."""

import argparse
import json
import os
import shutil
import subprocess
from pathlib import Path

p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--chio", type=Path, default=Path("chio"))
p.add_argument("--python", type=Path, required=True)
p.add_argument("--state", type=Path, required=True)
a = p.parse_args()
os.umask(0o077)
root = Path(__file__).resolve().parent
state = a.state.resolve()
state.mkdir(mode=0o700)
chio = str(Path(shutil.which(str(a.chio)) or str(a.chio)).resolve(strict=True))
commands = {
    "python": [str(a.python.absolute()), str(root / "python/recipes.py")],
    "typescript": [shutil.which("node"), str(root / "typescript/dist/recipes.js")],
    "rust": [str(root / "rust/target/debug/examples/recipes")],
}
for language, command in commands.items():
    folder = state / language
    folder.mkdir(mode=0o700)
    policy = folder / "policy.yaml"
    policy.write_text(
        """kernel:
  max_capability_ttl: 3600
  durable_admission_mode: all
capabilities:
  default:
    tools:
      - server: chio-ipc
        tool: '*'
        operations: [invoke, delegate]
        ttl: 3600
"""
    )
    config = {
        "schema": "chio.process.host.v1",
        "policy": str(policy),
        "mailboxes": [{"id": "jobs", "renewable_leases": True}],
        "limits": {"max_processes": 1, "max_depth": 0, "max_calls": 16},
    }
    (folder / "config.json").write_text(json.dumps(config))
    subprocess.run(
        [
            chio,
            "--json",
            "process",
            "init",
            "--state",
            str(folder / "host"),
            "--config",
            str(folder / "config.json"),
        ],
        check=True,
        stdout=(folder / "initialized.json").open("w"),
    )
    plan = {
        "schema": "chio.process.run.v1",
        "max_parallel": 1,
        "workers": [
            {
                "process": "root",
                "command": command,
                "cwd": str(root),
                "input": {},
                "depends_on": [],
                "max_attempts": 1,
                "timeout_seconds": 30,
            }
        ],
    }
    (folder / "plan.json").write_text(json.dumps(plan))
    r = subprocess.run(
        [
            chio,
            "process",
            "run",
            "--state",
            str(folder / "host"),
            "--plan",
            str(folder / "plan.json"),
        ],
        capture_output=True,
        text=True,
    )
    (folder / "report.json").write_text(r.stdout)
    (folder / "stderr.txt").write_text(r.stderr)
    if r.returncode or not json.loads(r.stdout)["complete"]:
        raise RuntimeError(f"{language} recipes failed; inspect {folder}")
print(json.dumps({"languages": list(commands), "recipes_passed": True}))
