"""Plan, and optionally run, N parallel Claude Code sessions in git worktrees, then report the merge points.

What you'll learn
  - What `claude --worktree <name>` gives each session: a fresh checkout at
    `<repo>/.claude/worktrees/<name>/` on a new branch `worktree-<name>`, sharing the repo's `.git`.
  - The checks to run before fanning out: branch-safe names, no duplicates, `.claude/worktrees/` in
    `.gitignore`, a `.worktreeinclude` for gitignored files such as `.env` (a worktree is a fresh
    checkout, so they're missing), and a total budget you're willing to spend (N runs × the per-run cap).
  - Why "split parallel tasks along file boundaries": two tasks that touch the same file are a merge
    conflict waiting to happen. The footprint check predicts it; `--execute` shows it happen.
  - That `claude -p` never cleans up its worktrees (there's no exit prompt), so a script must remove them.

How to run (from labs/)
  python3 core-4/worktree_fanout.py                      # dry run: the plan, the commands, the checks
  python3 core-4/worktree_fanout.py -n 2                 # only the first two tasks
  python3 core-4/worktree_fanout.py --tasks my-tasks.json --repo ~/code/app   # plan against your repo (read-only)
  python3 core-4/worktree_fanout.py --execute            # make real worktrees in a temp git copy, merge them, test
  python3 core-4/worktree_fanout.py --execute --real --model haiku --max-budget-usd 0.05
      # also runs one read-only `claude -p` per worktree (costs money; N × the per-run cap at most)
  --execute needs git. Nothing touches your repo: it works on a temp copy of common/samples/tiny-app.

What to observe
  - The overlap warning: `case-insensitive-codes` and `trim-codes` both touch tinyapp/pricing.py.
  - With --execute, `git worktree list` shows one checkout per task, `git diff --stat` per branch shows
    each footprint, and the merge report shows the predicted conflict: the fourth branch conflicts in
    tinyapp/pricing.py, while the others merge and the tests still pass.
  - The cleanup step: `git worktree remove` per worktree, the step a `-p` fan-out has to do itself.

Exercises
  1. Change `trim-codes` so it doesn't touch the `DISCOUNTS.get(...)` line (for example, strip the
     code in `Cart.discount` instead). Does the footprint check still warn? Does the merge still conflict?
  2. Reorder the tasks so `trim-codes` merges first. Which branch conflicts now, and why is "the order
     you merge in" a decision you have to make up front?
  3. Add a `.env` file to the sample (in a temp copy) and rerun the dry run against it with --repo.
     What does the .worktreeinclude check tell you, and what would a worktree be missing without it?
  4. With --real, compare the per-run `total_cost_usd` values with the total cap you set.

Docs: https://code.claude.com/docs/en/worktrees ; https://code.claude.com/docs/en/cli-reference (--worktree) ;
https://code.claude.com/docs/en/headless ; https://code.claude.com/docs/en/best-practices
"""
from __future__ import annotations

import argparse
import json
import os
import re
import shlex
import shutil
import subprocess
import sys
from dataclasses import dataclass, field
from pathlib import Path
from typing import Any, Dict, List, Optional, Sequence, Tuple

sys.dont_write_bytecode = True  # keep __pycache__ out of the lab folders
HERE = Path(__file__).resolve().parent
LABS = HERE.parent
sys.path.insert(0, str(LABS))
sys.path.insert(0, str(LABS / "core-1"))
from common.cc import (READ_ONLY_TOOLS, ClaudeNotFoundError, UnsafeRunError, add_real_args,  # noqa: E402
                       check_safe, find_claude, run_git, run_headless, summarize, temp_repo)
from common.pretty import c, header, kv, step, table  # noqa: E402

DEFAULT_TASKS = HERE / "samples" / "tasks.json"
SAMPLE_REPO = LABS / "common" / "samples" / "tiny-app"
OUT = HERE / "out"
WORKTREE_DIR = ".claude/worktrees"  # "created under .claude/worktrees/<name>/ at your repository root" (worktrees)
BRANCH_PREFIX = "worktree-"         # "on a new branch named worktree-<name>" (worktrees)
MAX_TOTAL_CEILING = 5.00            # same ceiling as common.cc's per-run cap



@dataclass
class Task:
    name: str
    prompt: str
    files: List[str]
    edits: List[Dict[str, str]] = field(default_factory=list)

    @property
    def branch(self) -> str:
        return BRANCH_PREFIX + self.name

    @property
    def path(self) -> str:
        return f"{WORKTREE_DIR}/{self.name}"


class LabError(Exception):
    """A problem with the inputs; main() prints it and exits 2."""


# ----------------------------------------------------------------------------
# Loading and checking tasks
# ----------------------------------------------------------------------------
def load_tasks(path: Path) -> List[Task]:
    if not path.is_file():
        raise LabError(f"tasks file {path} " + ("isn't a regular file" if path.exists() else "not found"))
    try:
        data = json.loads(path.read_text(encoding="utf-8"))
    except json.JSONDecodeError as e:
        raise LabError(f"{path} isn't valid JSON: {e.msg} (line {e.lineno})")
    raw = data.get("tasks") if isinstance(data, dict) else data
    if not isinstance(raw, list) or not raw:
        raise LabError(f"{path} must hold a non-empty list of tasks (or {{\"tasks\": [...]}})")
    tasks = []
    for i, t in enumerate(raw, 1):
        if not isinstance(t, dict):
            raise LabError(f"task #{i} must be an object with name, prompt and files")
        name, prompt, files = t.get("name"), t.get("prompt"), t.get("files", [])
        if not isinstance(name, str) or not name.strip():
            raise LabError(f"task #{i} needs a non-empty string 'name'")
        if not isinstance(prompt, str) or not prompt.strip():
            raise LabError(f"task {name!r} needs a non-empty string 'prompt'")
        if prompt.lstrip().startswith("-"):
            raise LabError(f"task {name!r}: a prompt must not start with '-' (the CLI would read it as a flag)")
        if not isinstance(files, list) or not all(isinstance(f, str) and f for f in files):
            raise LabError(f"task {name!r}: 'files' must be a list of paths")
        edits = t.get("simulated_edit", [])
        if not isinstance(edits, list) or not all(isinstance(e, dict) and {"file", "find", "replace"} <= set(e) for e in edits):
            raise LabError(f"task {name!r}: 'simulated_edit' must be a list of {{file, find, replace}} objects")
        tasks.append(Task(name.strip(), prompt.strip(), [f.strip().lstrip("./") for f in files], edits))
    return tasks


def name_problems(name: str) -> List[str]:
    """Why `worktree-<name>` wouldn't be a safe branch and directory name (git check-ref-format rules)."""
    probs = []
    if re.search(r"[\x00-\x20\x7f~^:?*\[\\]", name):
        probs.append("contains a space, control character or one of ~ ^ : ? * [ \\")
    if ".." in name or "@{" in name or "//" in name:
        probs.append("contains '..', '@{' or '//'")
    if name.startswith(("-", ".", "/")) or name.endswith((".", "/", ".lock")):
        probs.append("starts with - . / or ends with . / .lock")
    if "/" in name:
        probs.append("contains '/': the worktree directory would nest under .claude/worktrees/")
    if name.startswith("#"):
        probs.append("starts with '#': `--worktree \"#1234\"` means 'check out pull request 1234'")
    return probs


def footprint_overlaps(tasks: Sequence[Task]) -> List[Tuple[str, str, List[str]]]:
    """Pairs of tasks whose file footprints overlap (same file, or one is a directory containing the other)."""
    def touches(a: str, b: str) -> bool:
        a, b = a.rstrip("/"), b.rstrip("/")
        return a == b or a.startswith(b + "/") or b.startswith(a + "/")

    out = []
    for i, t in enumerate(tasks):
        for u in tasks[i + 1:]:
            shared = sorted({f for f in t.files for g in u.files if touches(f, g)})
            if shared:
                out.append((t.name, u.name, shared))
    return out


def repo_checks(repo: Path) -> List[Tuple[str, str, str]]:
    """(level, check, detail) for the repo the worktrees branch from. Read-only."""
    out: List[Tuple[str, str, str]] = []
    gi = repo / ".gitignore"
    lines = gi.read_text(encoding="utf-8", errors="replace").splitlines() if gi.is_file() else []
    ignored = any(ln.strip().rstrip("/") in (".claude/worktrees", "/.claude/worktrees", ".claude", "/.claude")
                  for ln in lines)
    if ignored:
        out.append(("ok", ".gitignore", ".claude/worktrees/ is ignored"))
    else:
        # Tip on the worktrees page: add .claude/worktrees/ to .gitignore.
        out.append(("warn", ".gitignore", "add `.claude/worktrees/` so worktree contents don't show as untracked files"))
    env_files = sorted(p.name for p in repo.glob(".env*") if p.is_file())
    wti = repo / ".worktreeinclude"
    if env_files and not wti.is_file():
        out.append(("warn", ".worktreeinclude", f"{', '.join(env_files)} won't exist in a fresh worktree; list them in "
                                                "a .worktreeinclude (gitignore syntax; only gitignored matches are copied)"))
    elif wti.is_file():
        out.append(("ok", ".worktreeinclude", "present: gitignored matches are copied into each new worktree"))
    else:
        out.append(("ok", ".worktreeinclude", "no .env-style files at the root, so nothing to copy"))
    if not (repo / ".git").exists():
        out.append(("info", "git", "not a git checkout here; --worktree needs a git repo with at least one commit"))
    # worktree.baseRef: "fresh" (default) branches from the remote default branch, "head" from local HEAD (worktrees).
    out.append(("info", "base", "`claude --worktree` branches from origin's default branch by default (worktree.baseRef "
                                "\"fresh\"); set \"head\" to carry unpushed commits. `git worktree add` uses your HEAD."))
    return out


# ----------------------------------------------------------------------------
# The plan
# ----------------------------------------------------------------------------
def claude_cmd(t: Task, max_turns: int, budget: float, model: Optional[str]) -> List[str]:
    """One headless session in its own worktree. `claude -p --worktree` skips the trust check (worktrees)."""
    # Plan mode keeps Claude from editing, but with auto mode available it still runs classifier-approved shell
    # commands while planning (permission-modes, plan mode), so the tool list is pinned to reads as well.
    argv = ["claude", "-p", t.prompt, "--worktree", t.name, "--permission-mode", "plan",
            "--tools", ",".join(READ_ONLY_TOOLS), "--allowedTools", ",".join(READ_ONLY_TOOLS),
            "--output-format", "json", "--max-turns", str(max_turns), "--max-budget-usd", f"{budget:g}"]
    if model:
        argv += ["--model", model]
    return argv


def print_plan(tasks: Sequence[Task], args: argparse.Namespace, repo: Path) -> int:
    """Print the dry-run plan. Returns the number of blocking problems."""
    blocking = 0
    step(1, f"Tasks ({len(tasks)})")
    rows = []
    for t in tasks:
        probs = name_problems(t.name)
        blocking += bool(probs)
        rows.append([t.name, t.path + "/", t.branch, ", ".join(t.files) or "-",
                     c("; ".join(probs), "red") if probs else c("ok", "green")])
    table(rows, ["task", "worktree", "branch", "files it should touch", "name"])
    dups = sorted({t.name for t in tasks if [u.name for u in tasks].count(t.name) > 1})
    if dups:
        blocking += 1
        print(c(f"  duplicate names: {', '.join(dups)} (a reused name reopens the existing worktree)", "red"))

    print()
    step(2, "Footprint overlaps (split parallel tasks along file boundaries)")
    overlaps = footprint_overlaps(tasks)
    if not overlaps:
        print("  " + c("none: every task touches its own files", "green"))
    for a, b, shared in overlaps:
        print("  " + c("warn", "yellow") + f"  {a} and {b} both touch {', '.join(shared)}: "
              "merge one before starting the other, or narrow a footprint")

    print()
    step(3, "Repository checks" + (f" ({repo})" if args.repo else " (common/samples/tiny-app)"))
    for level, check, detail in repo_checks(repo):
        color = {"ok": "green", "warn": "yellow", "info": "gray"}[level]
        print(f"  {c(level, color):<5} {check}: {detail}")

    print()
    step(4, "Budget")
    total = len(tasks) * args.max_budget_usd
    kv("per run", f"--max-turns {args.max_turns}, --max-budget-usd {args.max_budget_usd:g} (client-side estimate)")
    kv("worst case", f"{len(tasks)} × ${args.max_budget_usd:g} = ${total:.2f} against your --max-total-usd ${args.max_total_usd:.2f}")
    if total > args.max_total_usd + 1e-9:
        blocking += 1
        print(c("  over budget: lower -n or --max-budget-usd, or raise --max-total-usd (at most $5)", "red"))
    print(c("  Spend can pass a cap by up to one response, so leave headroom (cli-reference, --max-budget-usd).", "gray"))

    print()
    # Plan mode keeps Claude from editing files, but it isn't a sandbox: with auto mode available, classifier-approved
    # shell commands run during planning (permission-modes, plan mode). Read-only needs the tool list too.
    step(5, "Commands (run each in its own terminal, or background them; plan mode keeps them from editing files)")
    for t in tasks:
        print("  " + shlex.join(claude_cmd(t, args.max_turns, args.max_budget_usd, args.model))
              + f" > out/{t.name}.json")
    print(c("  Plan mode alone isn't a sandbox: with auto mode available, classifier-approved commands still run while it\n"
            "  plans, so the commands also pin --tools and --allowedTools to Read,Grep,Glob. A plan-mode -p run can cost far\n"
            "  more than a read-only one (about 15x in one recorded haiku run; LABS.md), so keep budget headroom. Switch to\n"
            "  acceptEdits only for tasks you'll review; each run edits its own worktree.", "gray"))
    print()
    print("  The same thing by hand (git creates the worktree, Claude runs inside it):")
    for t in tasks[:2]:
        print("  " + f"git worktree add {t.path} -b {t.branch}")
        print("  " + f"(cd {t.path} && " + shlex.join(["claude", "-p", t.prompt, "--permission-mode", "plan",
                                                         "--tools", ",".join(READ_ONLY_TOOLS), "--allowedTools",
                                                         ",".join(READ_ONLY_TOOLS),
                                                         "--max-turns", str(args.max_turns), "--max-budget-usd",
                                                         f"{args.max_budget_usd:g}"]) + ")")
    if len(tasks) > 2:
        print(c(f"  ... and {len(tasks) - 2} more", "gray"))

    print()
    step(6, "Cleanup (a -p run never removes its worktree)")
    print("  git worktree list")
    for t in tasks[:1]:
        print(f"  git worktree remove {t.path}        # if git says it's locked: git worktree unlock {t.path}")
    print("  git branch -d " + " ".join(t.branch for t in tasks) + "   # after you've merged them")
    return blocking


# ----------------------------------------------------------------------------
# --execute: real worktrees in a temp copy
# ----------------------------------------------------------------------------
def git(repo: Path, *argv: str, check: bool = True) -> subprocess.CompletedProcess:
    """git in the temp copy through common.cc.run_git: every inherited GIT_* variable stripped (a GIT_DIR exported by
    a git hook would otherwise beat cwd and act on the learner's repo), global/system config isolated, no signing or
    hooks, repo discovery capped at the temp_repo() root, and the fixed Lab identity and date."""
    p = run_git(repo, "-c", "merge.conflictstyle=merge", *argv, check=False)
    if check and p.returncode != 0:
        raise LabError(f"git {' '.join(argv)} failed: {(p.stderr or p.stdout).strip()[:200]}")
    return p


def apply_edits(wt: Path, t: Task) -> List[str]:
    """Apply a task's simulated edit (exact find/replace, once each). Returns problems."""
    problems = []
    for e in t.edits:
        f = wt / e["file"]
        if not f.is_file():
            problems.append(f"{e['file']}: file not found")
            continue
        text = f.read_text(encoding="utf-8")
        if text.count(e["find"]) != 1:
            problems.append(f"{e['file']}: the 'find' text occurs {text.count(e['find'])} times (need exactly 1)")
            continue
        f.write_text(text.replace(e["find"], e["replace"]), encoding="utf-8")
    return problems


def run_tests(repo: Path) -> str:
    """Run the sample's unittest suite; report the count and OK/FAILED without timings."""
    p = subprocess.run([sys.executable, "-m", "unittest"], cwd=str(repo), capture_output=True, text=True,
                       stdin=subprocess.DEVNULL, env=dict(os.environ, PYTHONDONTWRITEBYTECODE="1"), timeout=120)
    out = p.stderr + p.stdout
    ran = re.search(r"Ran (\d+) tests?", out)
    status = "OK" if re.search(r"^OK\b", out, re.M) else (re.search(r"^FAILED.*$", out, re.M) or [None])[0] or "?"
    return f"{ran.group(1) if ran else '?'} tests, {status}"


def execute(tasks: Sequence[Task], args: argparse.Namespace) -> int:
    if not shutil.which("git"):
        raise LabError("--execute needs git on PATH (install git, or run the dry run without --execute)")
    if args.real and not find_claude():
        raise LabError("--real needs the `claude` CLI on PATH. Install Claude Code (https://code.claude.com/docs/en/setup) "
                       "and sign in, or drop --real.")
    try:
        repo = temp_repo("tiny-app", git=True)
    except subprocess.CalledProcessError as e:
        raise LabError(f"couldn't create the temp git repo ({(e.stderr or b'').decode(errors='replace').strip()[:160]})")
    root = str(repo.parent)

    def clean(s: str) -> str:
        return s.replace(os.path.realpath(root), "<tmp>").replace(root, "<tmp>")

    print()
    header("Executing in a temp git copy of common/samples/tiny-app")
    (repo / ".gitignore").write_text(".claude/worktrees/\n__pycache__/\n", encoding="utf-8")
    git(repo, "add", ".gitignore")
    git(repo, "commit", "-q", "-m", "chore: ignore Claude worktrees")
    step(1, "Create one worktree per task (what `claude --worktree <name>` does)")
    made: List[Task] = []
    for t in tasks:
        git(repo, "worktree", "add", "-q", t.path, "-b", t.branch)
        made.append(t)
        print(f"  git worktree add {t.path} -b {t.branch}")
    print()
    print(clean(git(repo, "worktree", "list").stdout.rstrip()))

    if args.real:
        print()
        step("1b", "One read-only claude -p per worktree (real; costs money)")
        for t in made:
            try:
                run = run_headless(t.prompt + " Plan only: name the files and the change; don't edit anything.",
                                   real=True, cwd=repo / t.path, tools=READ_ONLY_TOOLS, permission_mode="dontAsk",
                                   max_turns=args.max_turns, max_budget_usd=args.max_budget_usd, model=args.model)
            except (UnsafeRunError, ClaudeNotFoundError) as e:
                raise LabError(str(e))
            s = summarize(run.events)
            kv(t.name, f"{s['subtype']} turns={s['turns']} cost=${(s['cost_usd'] or 0):.4f} "
                       f"tools={s['tool_calls_by_name']}")

    print()
    step(2, "Apply each task's simulated edit and commit it on its branch (fixed author and date)")
    for t in made:
        wt = repo / t.path
        problems = apply_edits(wt, t)
        for pr in problems:
            print(c(f"  {t.name}: {pr}", "yellow"))
        git(wt, "add", "-A")
        if git(wt, "diff", "--cached", "--quiet", check=False).returncode == 0:
            print(c(f"  {t.name}: nothing changed", "yellow"))
            continue
        git(wt, "commit", "-q", "-m", f"{t.name}: simulated edit")
        stat = git(repo, "diff", "--stat", f"main...{t.branch}").stdout.rstrip()
        print(f"  {c(t.branch, 'bold')}  {git(wt, 'rev-parse', '--short', 'HEAD').stdout.strip()}")
        for line in stat.splitlines():
            print("    " + line.strip())

    print()
    step(3, "Merge report: merge the branches into main in task order")
    predicted = {frozenset((a, b)): shared for a, b, shared in footprint_overlaps(made)}
    rows = []
    merged: List[str] = []
    for t in made:
        p = git(repo, "merge", "--no-ff", "--no-edit", "-m", f"merge {t.branch}", t.branch, check=False)
        if p.returncode == 0:
            merged.append(t.name)
            rows.append([t.branch, c("merged", "green"), "-"])
        else:
            conflicted = git(repo, "diff", "--name-only", "--diff-filter=U", check=False).stdout.split()
            git(repo, "merge", "--abort", check=False)
            with_whom = [m for m in merged if frozenset((m, t.name)) in predicted]
            rows.append([t.branch, c("CONFLICT", "red"), ", ".join(conflicted) +
                         (f" (overlap with {', '.join(with_whom)} was predicted)" if with_whom else "")])
    table(rows, ["branch", "result", "conflicting files"])
    print()
    kv("tests on main after the merges", run_tests(repo))

    print()
    step(4, "Cleanup: remove every worktree (a -p fan-out must do this itself)")
    for t in made:
        git(repo, "worktree", "remove", "--force", t.path, check=False)
        print(f"  git worktree remove {t.path}")
    git(repo, "worktree", "prune", check=False)
    left = [ln for ln in git(repo, "worktree", "list").stdout.splitlines() if WORKTREE_DIR in ln]
    kv("worktrees left", len(left))
    print(c("  The temp copy itself is deleted when this script exits (set LAB_KEEP_TMP=1 to keep it).", "gray"))
    return 0


def main() -> int:
    ap = argparse.ArgumentParser(description=__doc__.split("\n", 1)[0],
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--tasks", type=Path, default=DEFAULT_TASKS, help="tasks JSON (default core-4/samples/tasks.json)")
    ap.add_argument("-n", type=int, default=None, help="use only the first N tasks")
    ap.add_argument("--max-total-usd", type=float, default=2.00, help="cap on N × per-run budget (default 2.00, at most 5)")
    ap.add_argument("--execute", action="store_true", help="create the worktrees in a temp git copy and merge them")
    ap.add_argument("--json", action="store_true", help="also write the plan to core-4/out/fanout-plan.json")
    add_real_args(ap, max_turns=8, max_budget_usd=0.25)
    args = ap.parse_args()
    if args.n is not None and args.n < 1:
        ap.error("-n must be at least 1")
    if not 0 < args.max_total_usd <= MAX_TOTAL_CEILING:
        ap.error(f"--max-total-usd must be in (0, {MAX_TOTAL_CEILING:g}]")
    if args.real:
        args.execute = True
    if args.repo and args.execute:
        ap.error("--repo is for planning against your repo (read-only); --execute always works on a temp copy")
    repo = Path(args.repo).expanduser().resolve() if args.repo else SAMPLE_REPO
    if not repo.is_dir():
        ap.error(f"--repo {repo} is not a directory")
    try:
        # Same caps the shared runner enforces, checked up front for every planned run.
        check_safe(tools=READ_ONLY_TOOLS, permission_mode="plan", max_turns=args.max_turns,
                   max_budget_usd=args.max_budget_usd, model=args.model)
        tasks = load_tasks(args.tasks)
        if args.n is not None:
            tasks = tasks[: args.n]
        header(f"Worktree fan-out · {len(tasks)} task(s) · {'execute' if args.execute else 'dry run'}")
        blocking = print_plan(tasks, args, repo)
        if args.json:
            OUT.mkdir(exist_ok=True)
            plan = {"tasks": [{"name": t.name, "worktree": t.path, "branch": t.branch, "files": t.files,
                               "command": claude_cmd(t, args.max_turns, args.max_budget_usd, args.model)} for t in tasks],
                    "overlaps": [{"tasks": [a, b], "files": f} for a, b, f in footprint_overlaps(tasks)],
                    "worst_case_usd": round(len(tasks) * args.max_budget_usd, 4)}
            (OUT / "fanout-plan.json").write_text(json.dumps(plan, indent=2) + "\n", encoding="utf-8")
            print(c(f"\nwrote {OUT.relative_to(LABS)}/fanout-plan.json", "gray"))
        if args.execute:
            if blocking:
                raise LabError(f"{blocking} blocking problem(s) in the plan; fix them before --execute")
            return execute(tasks, args)
        print(c("\nDry run: nothing was created. Add --execute to try it in a temp git copy.", "gray"))
        return 0
    except UnsafeRunError as e:
        print(f"error: {e}", file=sys.stderr)
        return 2
    except LabError as e:
        print(f"error: {e}", file=sys.stderr)
        return 2


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