"""Authored wrong recipe, bounded for demonstration. Not an observed Codex defect."""
from pathlib import Path
import json
import subprocess
import sys

ROOT = Path(__file__).resolve().parents[1]
if (ROOT / "build/catalog.json").exists():
    raise SystemExit("run this teaching counterexample only in a fresh copy without a catalog")
proc = subprocess.Popen([sys.executable, "-u", "scripts/serve_catalog.py", "--port", "0"], cwd=ROOT)
result = {"authoredCounterexample": True, "buildStepReached": False}
try:
    code = proc.wait(timeout=1)
    if code:
        raise RuntimeError("server exited before demonstrating foreground blocking")
    result["buildStepReached"] = True
    subprocess.run([sys.executable, "scripts/build_catalog.py"], cwd=ROOT, check=True, timeout=10)
except subprocess.TimeoutExpired:
    result["foregroundServerBlockedNextStep"] = True
finally:
    if proc.poll() is None:
        proc.terminate()
    try:
        proc.wait(timeout=3)
    except subprocess.TimeoutExpired:
        proc.kill()
        proc.wait(timeout=3)
    result["serverExit"] = proc.returncode
    result["childStopped"] = proc.poll() is not None
    result["catalogExists"] = (ROOT / "build/catalog.json").exists()
print(json.dumps(result, sort_keys=True))
raise SystemExit(0 if result.get("foregroundServerBlockedNextStep") and result["childStopped"] and not result["catalogExists"] else 1)
