"""ADW Pipeline — run phase scripts and stop on failures unless ZTE is enabled."""
import json
import subprocess
import sys

PHASES = ["plan", "build", "test", "review", "document", "ship"]


def run_phase(phase, adw_id):
    r = subprocess.run(
        [sys.executable, f"adw_modules/adw_{phase}_iso.py", "--adw-id", adw_id],
        capture_output=True,
        text=True,
        timeout=300,
    )
    try:
        data = json.loads(r.stdout or "{}")
    except json.JSONDecodeError:
        data = {"stdout": r.stdout[:500]}
    data.update({"phase": phase, "ok": r.returncode == 0})
    if r.stderr:
        data["stderr"] = r.stderr[:500]
    return data


def run_pipeline(adw_id, zte=False):
    results = []
    for phase in PHASES:
        result = run_phase(phase, adw_id)
        results.append(result)
        if not result["ok"] and not zte:
            break
    return {"adw_id": adw_id, "zte": zte, "phases": results, "shipped": all(r["ok"] for r in results)}


if __name__ == "__main__":
    aid = sys.argv[sys.argv.index("--adw-id") + 1] if "--adw-id" in sys.argv else "test"
    print(json.dumps(run_pipeline(aid, "--zte" in sys.argv), indent=2))
