"""Sample actual user prompts per source to understand what they really look like.

Key findings:
- Codex CLI: first 1-3 user msgs are system-injected XML (<INSTRUCTIONS>, <environment_context>, # AGENTS.md)
- Gemini CLI: appends "--- Content from referenced files ---" with 100K+ chars of file content
- Claude Code: has slash commands like <command-name>/clear</command-name>
- Cursor: very terse (median 11 chars), often just "hi"
- Compaction msgs start with "This session is being continued from a previous conversation"

Run: /home/sagar/trace/.venv/bin/python3 analysis-14022026/session_view_scripts/research/01_sample_user_prompts.py
"""
import json
import os
import random
import statistics

DIR = os.path.join(os.path.dirname(__file__), "../viewer/public/data/sessions")
IDX = os.path.join(os.path.dirname(__file__), "../viewer/public/data/index.json")

with open(IDX) as f:
    index = json.load(f)

CODEX_PREFIXES = [
    "# AGENTS.md",
    "<INSTRUCTIONS>",
    "<environment_context>",
    "<repository_context>",
]
GEMINI_REF_SIG = "--- Content from referenced files ---"
COMPACTION_SIG = "This session is being continued from a previous conversation"

# ---- Part 1: Raw first user messages per source ----
print("=" * 60)
print("PART 1: RAW first user messages (as-is from data)")
print("=" * 60)

random.seed(42)
all_sessions = []
for dev in index["developers"].values():
    for s in dev["sessions"]:
        all_sessions.append(s)

for source in ["claude_code", "codex_cli", "gemini_cli", "cursor"]:
    source_sessions = [s for s in all_sessions if s["source"] == source]
    sample = random.sample(source_sessions, min(3, len(source_sessions)))

    print(f"\n===== {source.upper()} — sample raw user prompts =====")
    for s in sample:
        fpath = os.path.join(DIR, f'{s["id"]}.json')
        if not os.path.exists(fpath):
            continue
        with open(fpath) as f2:
            msgs = json.load(f2)
        user_msgs = [m for m in msgs if m["type"] == "user" and m.get("content")]
        if not user_msgs:
            continue
        first = user_msgs[0]["content"]
        print(f'  [{s["id"][:8]}] ({len(first)} chars): {repr(first[:400])}')
        if len(user_msgs) > 1:
            second = user_msgs[1]["content"]
            print(f"    2nd msg ({len(second)} chars): {repr(second[:300])}")
        print()

# ---- Part 2: Cleaned first prompts (stripping system noise) ----
print("\n" + "=" * 60)
print("PART 2: CLEANED first prompts (human-written part only)")
print("=" * 60)

first_prompts_by_source = {
    "claude_code": [],
    "codex_cli": [],
    "gemini_cli": [],
    "cursor": [],
}

for dev in index["developers"].values():
    for s in dev["sessions"]:
        fpath = os.path.join(DIR, f'{s["id"]}.json')
        if not os.path.exists(fpath):
            continue
        with open(fpath) as f2:
            msgs = json.load(f2)

        for m in msgs:
            if m["type"] != "user" or not m.get("content"):
                continue
            c = m["content"]

            # Skip codex system-injected messages
            if s["source"] == "codex_cli":
                if any(c.startswith(p) for p in CODEX_PREFIXES):
                    continue

            # Strip gemini file refs
            if s["source"] == "gemini_cli" and GEMINI_REF_SIG in c:
                c = c[: c.index(GEMINI_REF_SIG)].strip()

            # Skip compaction messages
            if c.startswith(COMPACTION_SIG):
                continue

            # Skip claude slash commands
            if c.startswith("<command-name>") or c.startswith("<command-message>"):
                continue

            first_prompts_by_source[s["source"]].append(c)
            break

for source, prompts in first_prompts_by_source.items():
    print(f"\n===== {source} — {len(prompts)} cleaned first prompts =====")
    lengths = [len(p) for p in prompts]
    if lengths:
        print(
            f"  Length: min={min(lengths)}, "
            f"median={statistics.median(lengths):.0f}, "
            f"mean={statistics.mean(lengths):.0f}, "
            f"max={max(lengths)}"
        )

    for p in random.sample(prompts, min(5, len(prompts))):
        print(f"  [{len(p)} chars] {repr(p[:200])}")
