"""Deep analysis of interruption patterns: position, tool interrupted, post-interrupt behavior.

Key findings:
- 507 total interruption events across 162 sessions
- Interrupted tools: Bash (272), ExitPlanMode (79), Edit (50), Write (15)
- Position: early(<33%)=134, mid(33-66%)=143, late(>66%)=230
- Post-interrupt: 87% user gave guidance, 13% session ended
- Early interrupts = AI misunderstood task. Late = AI went off on a specific action.

Run: /home/sagar/trace/.venv/bin/python3 analysis-14022026/session_view_scripts/research/02_interruption_patterns.py
"""
import json
import os
from collections import Counter

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")

CLAUDE_SIG = "doesn't want to proceed"
CODEX_SIG = "<turn_aborted>"

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

# ---- Part 1: Position + tool interrupted ----
print("=" * 60)
print("PART 1: Interruption position & tool analysis")
print("=" * 60)

interrupt_events = []

for dev in index["developers"].values():
    for s in dev["sessions"]:
        if s.get("interruptions", 0) == 0:
            continue
        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)

        total = len(msgs)
        for i, m in enumerate(msgs):
            is_interrupt = False
            if m["type"] == "tool_result" and CLAUDE_SIG in m.get("result", {}).get(
                "output", ""
            ):
                is_interrupt = True
            elif m["type"] == "user" and m.get("content", "").startswith(CODEX_SIG):
                is_interrupt = True

            if not is_interrupt:
                continue

            pos_pct = round(i / max(total, 1) * 100, 1)

            # What tool was interrupted? Walk backwards
            tool_name = "unknown"
            for j in range(i - 1, -1, -1):
                if msgs[j]["type"] == "tool_call" and msgs[j].get("tool"):
                    tool_name = msgs[j]["tool"]["tool_name"]
                    break

            # What did user do after?
            post_content = ""
            for j in range(i + 1, len(msgs)):
                if msgs[j]["type"] == "user" and msgs[j].get("content"):
                    post_content = msgs[j]["content"][:200]
                    break

            interrupt_events.append(
                {
                    "session_id": s["id"],
                    "source": s["source"],
                    "pos_pct": pos_pct,
                    "tool": tool_name,
                    "post_content": post_content,
                    "total_msgs": total,
                    "msg_index": i,
                }
            )

print(f"Total interruption events: {len(interrupt_events)}")

# Position distribution
early = sum(1 for x in interrupt_events if x["pos_pct"] < 33)
mid = sum(1 for x in interrupt_events if 33 <= x["pos_pct"] < 66)
late = sum(1 for x in interrupt_events if x["pos_pct"] >= 66)
print(f"Position: early(<33%)={early}, mid(33-66%)={mid}, late(>66%)={late}")

# Tool distribution
tool_counts = Counter(x["tool"] for x in interrupt_events)
print(f"Interrupted tools: {tool_counts.most_common(10)}")

# Post-interrupt actions
ended = sum(1 for x in interrupt_events if x["post_content"] == "")
guided = sum(1 for x in interrupt_events if x["post_content"] != "")
print(f"Post-interrupt: gave_guidance={guided}, session_ended={ended}")

# ---- Part 2: Context around interruptions (show 5 examples) ----
print("\n" + "=" * 60)
print("PART 2: Context around interruptions (msgs before/after)")
print("=" * 60)

count = 0
seen_sessions = set()
for dev in index["developers"].values():
    for s in dev["sessions"]:
        if s.get("interruptions", 0) == 0:
            continue
        if s["id"] in seen_sessions:
            continue
        seen_sessions.add(s["id"])

        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 i, m in enumerate(msgs):
            is_interrupt = False
            if m["type"] == "tool_result" and CLAUDE_SIG in m.get("result", {}).get(
                "output", ""
            ):
                is_interrupt = True
            elif m["type"] == "user" and m.get("content", "").startswith(CODEX_SIG):
                is_interrupt = True

            if is_interrupt and count < 5:
                count += 1
                print(
                    f'\n--- Interruption #{count} (session {s["id"][:8]}, {s["source"]}) ---'
                )
                for j in range(max(0, i - 2), min(len(msgs), i + 3)):
                    marker = " >>>" if j == i else "    "
                    mt = msgs[j]
                    content_preview = ""
                    if mt.get("content"):
                        content_preview = repr(mt["content"][:200])
                    elif mt.get("tool"):
                        content_preview = f'tool={mt["tool"]["tool_name"]}'
                    elif mt.get("result"):
                        content_preview = f'status={mt["result"]["status"]}, output={repr(mt["result"]["output"][:150])}'
                    print(f'{marker} [{j}] {mt["type"]}: {content_preview}')
        if count >= 5:
            break
    if count >= 5:
        break

# ---- Part 3: Post-interrupt user messages ----
print("\n" + "=" * 60)
print("PART 3: Sample post-interrupt user messages")
print("=" * 60)

for x in interrupt_events[:15]:
    if x["post_content"]:
        print(
            f'  [{x["pos_pct"]}% into session, interrupted {x["tool"]}]: {repr(x["post_content"][:150])}'
        )
