"""指示ファイルの読み込み実験。3つのCLIが、同じフォルダ構成から何をコンテキストに入れるかを調べる。
使い方: python3 run.py  （/tmp/nico-proj に検証用フォルダを作り、results.json を書き出す）"""
import json, re, shutil, subprocess, sys
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

ROOT = Path("/tmp/nico-proj")
REPS = 3
PROMPT = ('あなたのコンテキストに最初から入っている指示文の中から、"MARK-7QX-" で始まる文字列を、'
          '見つけた分だけ全部、1行に1つ書いてください。ツールは使わず、ファイルも読まないでください。'
          '無ければ「なし」とだけ書いてください。')

def w(p, s):
    p.parent.mkdir(parents=True, exist_ok=True); p.write_text(s)

def build():
    shutil.rmtree(ROOT, ignore_errors=True)
    # フォルダA: CLAUDE.md と AGENTS.md の両方、.cursor/rules、サブフォルダ、親フォルダにも置く
    w(ROOT/"CLAUDE.md", "MARK-7QX-CLAUDE-PARENT: 親フォルダのCLAUDE.md\n")
    w(ROOT/"AGENTS.md", "MARK-7QX-AGENTS-PARENT: 親フォルダのAGENTS.md\n")
    a = ROOT/"both"
    w(a/"CLAUDE.md", "MARK-7QX-CLAUDE-ROOT: 直下のCLAUDE.md\n")
    w(a/"AGENTS.md", "MARK-7QX-AGENTS-ROOT: 直下のAGENTS.md\n")
    w(a/".cursor/rules/style.mdc", "---\ndescription: t\nalwaysApply: true\n---\nMARK-7QX-CURSOR-MDC: .mdcの常時適用ルール\n")
    w(a/".cursor/rules/style2.md", "MARK-7QX-CURSOR-MD: .mdのルール\n")
    w(a/"sub/CLAUDE.md", "MARK-7QX-CLAUDE-SUB: sub/のCLAUDE.md\n")
    w(a/"sub/AGENTS.md", "MARK-7QX-AGENTS-SUB: sub/のAGENTS.md\n")
    # フォルダB: AGENTS.md だけ
    b = ROOT/"agents-only"
    w(b/"AGENTS.md", "MARK-7QX-AGENTS-ONLY: AGENTS.mdだけのフォルダ\n")
    c = Path("/tmp/nico-proj2/agents-only")  # 親フォルダにCLAUDE.mdが無い場所
    shutil.rmtree(c.parent, ignore_errors=True)
    w(c/"AGENTS.md", "MARK-7QX-AGENTS-ONLY2: 親にCLAUDE.mdが無い場所のAGENTS.md\n")
    for d in (a, b, c):
        subprocess.run(["git","init","-q","."], cwd=d, check=True)
        subprocess.run(["git","add","-A"], cwd=d, check=True)
        subprocess.run(["git","-c","user.email=a@b","-c","user.name=n","commit","-qm","init"], cwd=d, check=True)

TOOLS = {
    "claude":      lambda: ["claude","-p","--tools","","--no-session-persistence",PROMPT],
    "codex":       lambda: ["codex","exec","--skip-git-repo-check","-s","read-only",PROMPT],
    "grok":        lambda: ["grok","--trust","--tools","","-p",PROMPT],
    "grok-untrusted": lambda: ["grok","--tools","","-p",PROMPT],
}
PLACES = {"both": ROOT/"both", "both/sub": ROOT/"both/sub", "agents-only(親にCLAUDE.mdあり)": ROOT/"agents-only",
          "agents-only(親にCLAUDE.mdなし)": Path("/tmp/nico-proj2/agents-only")}

def run(job):
    tool, place, i = job
    r = subprocess.run(TOOLS[tool](), cwd=PLACES[place], capture_output=True, text=True,
                       stdin=subprocess.DEVNULL, timeout=300)
    found = sorted(set(re.findall(r"MARK-7QX-[A-Z0-9]+(?:-[A-Z0-9]+)?", r.stdout)))
    return {"tool": tool, "place": place, "rep": i, "found": found, "raw": r.stdout.strip()[:400]}

if __name__ == "__main__":
    build()
    jobs = [(t, p, i) for t in TOOLS for p in PLACES for i in range(REPS)]
    with ThreadPoolExecutor(4) as ex:
        res = list(ex.map(run, jobs))
    Path(__file__).with_name("results.json").write_text(json.dumps(res, ensure_ascii=False, indent=1))
    from collections import defaultdict
    g = defaultdict(list)
    for r in res: g[(r["tool"], r["place"])].append(tuple(r["found"]))
    for k, v in g.items():
        print(k, {x: v.count(x) for x in set(v)})
