#!/usr/bin/env python3
"""Replay the packaged synthetic workflow in isolated n8n; no product checkout."""
from __future__ import annotations

import argparse
import json
import re
import subprocess
import uuid
from pathlib import Path


def main():
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--package", type=Path, default=Path(__file__).resolve().parent)
    parser.add_argument("--output", type=Path, default=Path("replay-result"))
    args = parser.parse_args()
    package, output = args.package.resolve(), args.output.resolve()
    fixture = json.loads((package / "invoices.json").read_text())
    harness = json.loads((package / "sandbox-harness.json").read_text())
    image = "docker.n8n.io/n8nio/n8n:2.39.10"
    inspected = subprocess.run(["docker", "image", "inspect", image, "--format", "{{.Id}}"], capture_output=True, text=True, check=True)
    container = "processscout-public-proof-" + uuid.uuid4().hex[:12]
    # The CLI ID is supplied by this package, not interpreted as shell input.
    workflow_id = harness["id"]
    if not re.fullmatch(r"[A-Za-z0-9]{1,21}", workflow_id):
        raise SystemExit("Unsupported sandbox workflow ID")
    command = ["docker", "run", "--rm", "--network", "none", "--name", container,
               "--cap-drop", "ALL", "--security-opt", "no-new-privileges", "--memory", "2g", "--cpus", "2",
               "-e", "N8N_DIAGNOSTICS_ENABLED=false", "-e", "N8N_VERSION_NOTIFICATIONS_ENABLED=false",
               "-e", "N8N_TEMPLATES_ENABLED=false", "-v", str(package) + ":/proof:ro", "--entrypoint", "sh", inspected.stdout.strip(),
               "-c", "n8n import:workflow --input=/proof/sandbox-harness.json && n8n execute --id=" + workflow_id + " --rawOutput"]
    try:
        result = subprocess.run(command, capture_output=True, text=True, timeout=180, check=False)
    finally:
        subprocess.run(["docker", "rm", "-f", container], capture_output=True, check=False)
    raw = (result.stdout + result.stderr).replace(str(package), "<proof-package>")
    execution = None
    for match in re.finditer(r"(?m)^\{", raw):
        try:
            candidate, _ = json.JSONDecoder().raw_decode(raw[match.start():])
        except json.JSONDecodeError:
            continue
        if isinstance(candidate, dict) and "resultData" in candidate.get("data", {}):
            execution = candidate
    output.mkdir(parents=True, exist_ok=True)
    (output / "n8n-cli.log").write_text(raw)
    (output / "n8n-execution.json").write_text(json.dumps(execution, indent=2) + "\n")
    run_data = execution["data"]["resultData"].get("runData", {}) if execution else {}
    cases = []
    for case in fixture["cases"]:
        values = [item["json"] for run in run_data.get("rule-" + case["id"], [])
                  for stream in run.get("data", {}).get("main", []) for item in (stream or [])]
        expected = {"invoice_id": case["id"], "queue": case["expected"]}
        passed = len(values) == 1 and all(values[0].get(key) == value for key, value in expected.items())
        cases.append({"id": case["id"], "expected": expected, "actual": values, "status": "passed" if passed else "failed"})
    passed = bool(execution) and execution.get("status") == "success" and all(case["status"] == "passed" for case in cases)
    report = {"status": "passed" if passed else "failed", "engine_status": execution.get("status") if execution else None,
              "docker_image": image, "image_id": inspected.stdout.strip(), "cases": cases,
              "boundary": "Synthetic local CLI replay only; no compilation, product deployment, live schedule or human approval."}
    (output / "run-result.json").write_text(json.dumps(report, indent=2) + "\n")
    print(json.dumps(report, indent=2))
    return 0 if passed else 1


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