#!/usr/bin/env python3
"""Print a Claude Code session log as the steps of the agent loop.

Lecture 4, demonstration 2. Claude Code writes every session to
~/.claude/projects/<folder>/<session>.jsonl. Each line is one event: a user
message, a model reply (thinking, text or a tool call) or a tool result.

    python3 transcript.py              # latest session of the current folder
    python3 transcript.py FILE.jsonl   # a given session
    python3 transcript.py --raw        # also print one raw JSON line

Standard library only.
"""

import argparse
import json
import re
import sys
from collections import Counter
from pathlib import Path


def latest_log():
    projects = Path.home() / ".claude" / "projects"
    here = projects / re.sub(r"[^A-Za-z0-9]", "-", str(Path.cwd()))
    logs = sorted(here.glob("*.jsonl"), key=lambda p: p.stat().st_mtime)
    if not logs:
        logs = sorted(projects.glob("*/*.jsonl"), key=lambda p: p.stat().st_mtime)
    if not logs:
        sys.exit(f"No session logs under {projects}")
    return logs[-1]


def one_line(value, width=90):
    if isinstance(value, list):
        value = " ".join(b.get("text", "") for b in value if isinstance(b, dict))
    text = " ".join(str(value).split())
    return text if len(text) <= width else text[:width - 1] + "…"


def describe_call(block):
    args = block.get("input") or {}
    main = next((args[k] for k in ("command", "file_path", "pattern", "url", "query", "prompt", "description")
                 if k in args), json.dumps(args, ensure_ascii=False))
    return f"{block.get('name')}: {one_line(main, 70)}"


def main():
    parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    parser.add_argument("log", nargs="?")
    parser.add_argument("--raw", action="store_true", help="also print the first tool call as raw JSON")
    args = parser.parse_args()
    path = Path(args.log) if args.log else latest_log()
    print(f"Log: {path}\n")

    step, calls, usage_by_message, raw_shown = 0, Counter(), {}, False
    for line in path.read_text().splitlines():
        try:
            event = json.loads(line)
        except json.JSONDecodeError:
            continue
        kind, message = event.get("type"), event.get("message")
        if kind not in ("user", "assistant") or not isinstance(message, dict) or event.get("isMeta"):
            continue
        side = "  (sub-agent)" if event.get("isSidechain") else ""
        if kind == "assistant" and message.get("usage"):
            usage_by_message[message.get("id")] = message["usage"]
        content = message.get("content")
        blocks = content if isinstance(content, list) else [{"type": "text", "text": content}]
        for block in blocks:
            if not isinstance(block, dict):
                continue
            btype = block.get("type")
            if kind == "user" and btype == "text":
                text = block.get("text", "")
                if text.startswith("<") or "system-reminder" in text:
                    continue
                label, body = "user", one_line(text)
            elif kind == "user" and btype == "tool_result":
                label, body = "  tool result", ("ERROR " if block.get("is_error") else "") + one_line(block.get("content"))
            elif btype == "thinking":
                label, body = "model", "(thinking; the text is not returned)"
            elif btype == "text":
                label, body = "model", one_line(block.get("text"))
            elif btype == "tool_use":
                calls[block.get("name")] += 1
                label, body = "model → tool", describe_call(block)
                if args.raw and not raw_shown:
                    raw_shown = True
                    print(json.dumps(block, ensure_ascii=False, indent=2)[:1500])
            else:
                continue
            step += 1
            print(f"{step:4d}  {label:<13} {body}{side}")

    if usage_by_message:
        last = list(usage_by_message.values())[-1]
        context = sum(last.get(k) or 0 for k in ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
        written = sum(u.get("output_tokens") or 0 for u in usage_by_message.values())
        read = sum(sum(u.get(k) or 0 for k in ("input_tokens", "cache_read_input_tokens", "cache_creation_input_tokens"))
                   for u in usage_by_message.values())
        print(f"\nModel calls: {len(usage_by_message)} · tool calls: {sum(calls.values())} "
              f"({', '.join(f'{name} ×{n}' for name, n in calls.most_common())})")
        print(f"Context at the last call: {context:,} tokens · read in total: {read:,} · written: {written:,}")


if __name__ == "__main__":
    main()
