# python3 run.py <arm> <idea id> <rep>   arms: plain, ccgs
# Fresh `claude -p --model haiku` session in a new folder (ccgs: a copy of the template repo). After each turn,
# if no game exists yet, resume the same session with a fixed reply, up to 5 turns. Keeps the game folder.
import glob, json, os, shutil, subprocess, sys, time

HERE = os.path.dirname(os.path.abspath(__file__))
REPO = os.path.join(os.path.dirname(HERE), "repo")
IDEAS = {
    "fish": "a fishing game where the rare fish only bite at dusk",
    "ice": "a top-down racing game on an icy track where the car slides",
    "seed": "a tower defense game where towers are seeds you plant that grow stronger over time",
    "grav": "a platformer where you can flip gravity once per jump",
    "tide": "a match-3 puzzle where every match pushes a rising tide back down",
}
REPLY = "You pick every answer. Build it."

arm, idea, rep = sys.argv[1], sys.argv[2], sys.argv[3]
name = f"{arm}-{idea}-{rep}"
out = f"{HERE}/runs/{name}"
if os.path.exists(f"{out}/log.jsonl"):
    sys.exit(0)
work = f"{HERE}/work/{name}"
shutil.rmtree(work, ignore_errors=True)
if arm == "ccgs":
    shutil.copytree(REPO, work, ignore=shutil.ignore_patterns(".git"))
else:
    os.makedirs(work)
subprocess.run("git init -q && git add -A && git -c user.email=t@t -c user.name=t commit -qm init --allow-empty",
               shell=True, cwd=work)
first = (f"/prototype {IDEAS[idea]}" if arm == "ccgs" else
         f"Make me a playable browser game: {IDEAS[idea]}. Put it in prototypes/<name>/ as a folder that opens with a double-click on index.html.")


def game():
    hits = [p for p in glob.glob(f"{work}/**/index.html", recursive=True) if "/.claude/" not in p and "/node_modules/" not in p]
    return sorted(hits, key=os.path.getmtime)[-1] if hits else None


os.makedirs(out, exist_ok=True)
log = open(f"{out}/log.jsonl", "w")
sid, t0 = None, time.time()
for turn in range(5):
    cmd = ["claude", "-p", first if turn == 0 else REPLY, "--model", "haiku", "--setting-sources", "project",
           "--output-format", "stream-json", "--verbose", "--permission-mode", "bypassPermissions"]
    if sid:
        cmd += ["--resume", sid]
    try:
        r = subprocess.run(cmd, cwd=work, capture_output=True, text=True, timeout=2400)
        body = r.stdout
    except subprocess.TimeoutExpired as e:
        body = e.stdout if isinstance(e.stdout, str) else (e.stdout or b"").decode()
        log.write(json.dumps({"type": "timeout", "turn": turn}) + "\n")
    for line in body.splitlines():
        if line.strip():
            log.write(line + "\n")
            try:
                m = json.loads(line)
                sid = m.get("session_id") or sid
            except Exception:
                pass
    log.write(json.dumps({"type": "turn_end", "turn": turn, "game": game()}) + "\n")
    log.flush()
    if game():
        break
g = game()
log.write(json.dumps({"type": "done", "wall": time.time() - t0, "game": g and os.path.relpath(g, work)}) + "\n")
log.close()
if g:
    shutil.copytree(os.path.dirname(g), f"{out}/game", dirs_exist_ok=True)
