"""grill-me vs no skill, with a simulated user who holds a hidden 10-point spec. haiku everywhere.
python3 sim.py [reps] -> runs/<cond>-<rep>/ (transcript.md, plan.md, score.json); results.json
Agent: claude -p in its own folder (grill-me + grilling skills for the grill condition), --continue between rounds.
User: a fresh claude -p each round that sees only the spec and the agent's last message, and answers only what was asked.
Judge: a fresh claude -p that checks plan.md against the 10 points."""
import json, re, shutil, subprocess, sys, time
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path
HERE = Path(__file__).resolve().parent
SK = HERE / "src/mattpocock_skills/skills/productivity"
SPEC = [
    "Both the referrer and the invited friend get 1 month of Plus free.",
    "A referrer can earn at most 12 free months per year.",
    "The reward is granted only after the friend has been active for 7 days, not at signup.",
    "No reward when the friend shares the referrer's device ID or payment method.",
    "Launch on iOS and Android only; invite links open the app store; web comes later.",
    "Rewards are Plus credit only, never cash or gift cards.",
    "A referrer who already pays for Plus gets the next renewal pushed back by a month.",
    "It must launch by December 15, before the New Year resolution season.",
    "Attribution uses a referral code in a deep link, with a 30-day attribution window.",
    "The referrer never sees the friend's habits, only that the friend joined.",
]
OPEN = "I want to add a referral program to Tidepool, my habit tracker app (free tier plus a $4/month Plus plan). Help me plan it."
DONE = "That's everything from me. Write the final plan to plan.md in this folder now."
MAX_ROUNDS = 6

def claude(prompt, cwd, cont=False, tools=("Read", "Write", "Edit", "Glob", "Grep", "Skill")):
    cmd = ["claude", "-p", prompt, "--model", "haiku", "--setting-sources", "project", "--output-format", "json"]
    if tools: cmd += ["--allowedTools", *tools]
    if cont: cmd.insert(3, "--continue")
    j = json.loads(subprocess.run(cmd, cwd=cwd, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=900).stdout)
    return j.get("result", ""), j.get("total_cost_usd", 0)

def user_reply(agent_msg, tmp):
    p = ("You are the founder of Tidepool answering your product assistant. Your private plan is below. Answer ONLY the questions the "
         "assistant asked, briefly, in plain sentences, from your plan. If it recommends something that differs from your plan, say so "
         "and give your plan's answer. If it asks about something your plan does not cover, say you have no preference. Never volunteer "
         "points it did not ask about. If its message asks no question, reply exactly: NO QUESTIONS.\n\nYour plan:\n- " + "\n- ".join(SPEC) +
         "\n\nAssistant's message:\n" + agent_msg)
    return claude(p, tmp, tools=())

def judge(plan, tmp):
    p = ("Below is a product plan and 10 requirements. For each requirement, answer true only if the plan states it correctly (same "
         "numbers and rules), false if it is missing, vague or different. Reply with only a JSON array of 10 booleans.\n\nRequirements:\n" +
         "\n".join(f"{i+1}. {s}" for i, s in enumerate(SPEC)) + "\n\nPlan:\n" + plan)
    txt, cost = claude(p, tmp, tools=())
    m = re.search(r"\[[^\]]*\]", txt)
    return (json.loads(m.group(0).lower()) if m else []), cost

def one(job):
    cond, rep = job
    d = HERE / "runs" / f"{cond}-{rep}"; tmp = HERE / "runs" / f"{cond}-{rep}-user"
    for x in (d, tmp): shutil.rmtree(x, ignore_errors=True); x.mkdir(parents=True)
    (d / ".claude/skills").mkdir(parents=True)
    if cond == "grill":
        for s in ("grill-me", "grilling"): shutil.copytree(SK / s, d / ".claude/skills" / s)
    t0 = time.time(); cost = 0; log = []; questions = 0; rounds = 0
    msg, c = claude(("/grill-me " if cond == "grill" else "") + OPEN, d); cost += c; log.append(("assistant", msg))
    while rounds < MAX_ROUNDS and not (d / "plan.md").exists():
        ans, c = user_reply(msg, tmp); cost += c; log.append(("user", ans))
        if ans.strip().startswith("NO QUESTIONS"): break
        rounds += 1; questions += msg.count("?")
        msg, c = claude(ans, d, cont=True); cost += c; log.append(("assistant", msg))
    if not (d / "plan.md").exists():
        msg, c = claude(DONE, d, cont=True); cost += c; log.append(("user", DONE)); log.append(("assistant", msg))
    plan = (d / "plan.md").read_text() if (d / "plan.md").exists() else msg
    score, c = judge(plan, tmp); cost += c
    (d / "transcript.md").write_text("\n\n".join(f"## {who}\n\n{t}" for who, t in log))
    r = dict(cond=cond, rep=rep, rounds=rounds, question_marks=questions, plan_words=len(plan.split()), covered=sum(score),
             score=score, secs=round(time.time() - t0), cost=round(cost, 4))
    (d / "score.json").write_text(json.dumps(r, indent=1))
    return r

if __name__ == "__main__":
    reps = int(sys.argv[1]) if len(sys.argv) > 1 else 3
    with ThreadPoolExecutor(4) as ex:
        res = list(ex.map(one, [(c, r) for r in range(1, reps + 1) for c in ("base", "grill")]))
    json.dump(res, open(HERE / "results.json", "w"), indent=1)
    for r in res: print(r)
