"""Show one complete session per source type with full message flow.

Useful for understanding the exact message sequence and what fields are populated.

Run: /home/sagar/trace/.venv/bin/python3 analysis-14022026/session_view_scripts/research/05_session_per_source_example.py
"""
import json
import os

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)


def show_session(s, max_msgs=30):
    """Print a session's message flow."""
    print(f'\n{"=" * 70}')
    print(
        f'SESSION: {s["id"][:16]}... | source={s["source"]} | model={s["model"]}'
    )
    print(
        f'repo={s.get("repo_name")} | cwd={s.get("cwd")}'
    )
    print(
        f'msgs={s["total_messages"]} | user={s["user_messages"]} | '
        f'assistant={s["assistant_messages"]} | tools={s["tool_calls"]} | '
        f'interrupts={s.get("interruptions", 0)}'
    )
    print(f'{s["start"]} → {s["end"]}')
    print("=" * 70)

    fpath = os.path.join(DIR, f'{s["id"]}.json')
    if not os.path.exists(fpath):
        print("  (session file not found)")
        return
    with open(fpath) as f2:
        msgs = json.load(f2)

    for i, m in enumerate(msgs[:max_msgs]):
        ts = m["timestamp"][11:19] if m.get("timestamp") else "??:??:??"
        mtype = m["type"]

        if mtype == "user":
            content = m.get("content", "")[:300]
            print(f"\n  [{i:3d}] {ts} 👤 USER ({len(m.get('content', ''))} chars)")
            print(f"         {repr(content)}")

        elif mtype == "assistant":
            content = m.get("content", "")[:300]
            model = m.get("model", "")
            print(f"\n  [{i:3d}] {ts} 🤖 ASSISTANT ({len(m.get('content', ''))} chars) model={model}")
            print(f"         {repr(content)}")

        elif mtype == "tool_call":
            tool = m.get("tool", {})
            name = tool.get("tool_name", "?")
            inp = tool.get("tool_input", "")[:150]
            print(f"  [{i:3d}] {ts} 🔧 TOOL_CALL: {name}")
            print(f"         input: {inp}")

        elif mtype == "tool_result":
            result = m.get("result", {})
            status = result.get("status", "?")
            output = result.get("output", "")[:150]
            print(f"  [{i:3d}] {ts} 📋 TOOL_RESULT: {status}")
            print(f"         output: {repr(output)}")

        else:
            content = m.get("content", "")[:100]
            print(f"  [{i:3d}] {ts} ℹ️  {mtype}: {repr(content)}")

    if len(msgs) > max_msgs:
        print(f"\n  ... ({len(msgs) - max_msgs} more messages)")


# Pick one interesting session per source
sources_shown = set()
for dev in index["developers"].values():
    for s in dev["sessions"]:
        if s["source"] in sources_shown:
            continue
        # Pick sessions with at least some tool usage and a few user messages
        if s["tool_calls"] >= 3 and s["user_messages"] >= 2:
            sources_shown.add(s["source"])
            show_session(s)
        if len(sources_shown) >= 4:
            break
    if len(sources_shown) >= 4:
        break

# Also show one session with interruptions
print("\n\n" + "#" * 70)
print("# SESSION WITH INTERRUPTIONS")
print("#" * 70)

for dev in index["developers"].values():
    for s in dev["sessions"]:
        if s.get("interruptions", 0) >= 2 and s["tool_calls"] >= 5:
            show_session(s, max_msgs=40)
            break
    else:
        continue
    break
