#!/bin/sh
""":"
case "$0" in
    # Inside the app: always this bundle's Python, never a home inherited from another one.
    *.app/Contents/Resources/*) bundle=${0%%.app/Contents/Resources/*}.app
                                export PYTHONHOME="$bundle/Contents/Resources/python" ;;
esac
exec "$PYTHONHOME/bin/python3" -I -S -B "$0" "$@"
": """
__doc__ = """Sessions: a digest of Claude Code (and Codex) conversations, by project.

    bin/sessions                      this Mac: ~/.claude/projects/*/*.jsonl
    bin/sessions --since 2026-10-01   only sessions touched on or after that day
    bin/sessions --codex              also ~/.codex/sessions (date, cwd, first prompt)
    bin/sessions --json               machine-readable instead of the text digest

For each project folder it prints the number of sessions, the date range and
the user turns, then one line per session: id (first 8 chars), first and last
day, turns, title, and the first 120 characters of the opening prompt. Days are
this Mac's own (the sessions keep UTC times): a session at 01:00 in Cairo is
dated that day, not the day before.

The title is the custom title if you set one, else the AI title, else the
summary line, else "(untitled)". A user turn is a real message from you:
tool results, interruptions and sidechain (sub-agent) lines are not counted.
Editor wrappers like <ide_opened_file> are stripped from the opening prompt.

Nothing is `cat`-ed and nothing is written. It reads only this Mac; it
never needs the life folder.

Codex keeps one `rollout-*.jsonl` per session under ~/.codex/sessions/YYYY/MM/DD/.
The first line is `session_meta` (id, timestamp, cwd) and the first
`event_msg` of type `user_message` is the opening prompt. A file that does not
look like that is reported as "format not understood", not guessed at.

In a demo folder (`demo: true` in the life folder's config.json) it reads
nothing and says NOT ESTABLISHED: a demo never shows the real Mac's sessions.

Exit status: 0, or 2 if a root could not be read.
"""
import datetime
import glob
import json
import os
import re
import sys

sys.dont_write_bytecode = True  # no __pycache__ beside the engine's scripts
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import lifecfg  # noqa: E402

# The home read is lifecfg.scan_home(): the real one, or ARGONI_SCAN_HOME for a made-up Mac.
CLAUDE_ROOT = lifecfg.expand_mac("~/.claude/projects")
CODEX_ROOT = lifecfg.expand_mac("~/.codex/sessions")

TAGRE = re.compile(
    r"<(ide_opened_file|ide_selection|system-reminder|local-command-caveat|"
    r"local-command-stdout|command-message|command-name|command-args|task-notification)>.*?</\1>", re.S)
SKIP = ("[Request interrupted",)


def first_text(c):
    if isinstance(c, str):
        t = c
    elif isinstance(c, list):
        t = "\n".join(b.get("text", "") for b in c
                      if isinstance(b, dict) and b.get("type") == "text")
    else:
        t = ""
    return TAGRE.sub("", t).strip()


def is_real_user(line):
    m = line.get("message", {})
    if not isinstance(m, dict) or m.get("role") != "user":
        return False
    c = m.get("content")
    if isinstance(c, list) and all(isinstance(b, dict) and b.get("type") == "tool_result" for b in c):
        return False
    t = first_text(c)
    if not t or t.startswith(SKIP):
        return False
    if line.get("isSidechain"):
        return False
    return True


def scan_claude(path):
    """One Claude Code session file -> dict, or None if it has no timestamps."""
    ai = custom = summary = first = cwd = None
    n = nasst = 0
    ts = []
    try:
        fh = open(path, encoding="utf-8", errors="replace")
    except OSError:
        return None
    with fh:
        for raw in fh:
            try:
                line = json.loads(raw)
            except ValueError:
                continue
            t = line.get("type")
            if t == "ai-title":
                ai = line.get("aiTitle")
            elif t == "custom-title":
                custom = line.get("customTitle")
            elif t == "summary":
                summary = line.get("summary")
            elif t == "user":
                if line.get("timestamp"):
                    ts.append(line["timestamp"])
                if is_real_user(line):
                    n += 1
                    if first is None:
                        first = re.sub(r"\s+", " ", first_text(line["message"]["content"]))[:120]
                cwd = cwd or line.get("cwd")
            elif t == "assistant":
                nasst += 1
                if line.get("timestamp"):
                    ts.append(line["timestamp"])
    if not ts:
        return None
    days = sorted(local_day(t) for t in ts)
    return {"id": os.path.basename(path)[:8], "first": days[0], "last": days[-1],
            "turns": n, "assistant": nasst, "title": custom or ai or summary or "(untitled)",
            "prompt": first or "", "cwd": cwd or ""}


def local_day(stamp):
    """YYYY-MM-DD on this Mac's clock for a session's ISO time ("...Z" is UTC); a time
    without a zone is taken as it is written."""
    stamp = str(stamp or "")
    # Python 3.9 reads only 3 or 6 digits after the seconds: ".12Z" and ".1234567Z" made 6.
    iso = re.sub(r"\.(\d+)", lambda m: "." + (m.group(1) + "000000")[:6], stamp, count=1)
    try:
        t = datetime.datetime.fromisoformat(iso.replace("Z", "+00:00"))
    except ValueError:
        return stamp[:10]
    return (t.astimezone() if t.tzinfo else t).date().isoformat()


def scan_root(root, pattern):
    """{project: [session, ...]} for every jsonl matching pattern under root."""
    projects = {}
    for f in sorted(glob.glob(os.path.join(root, pattern), recursive=True)):
        s = scan_claude(f)
        if s is None:
            continue
        key = os.path.relpath(os.path.dirname(f), root)
        projects.setdefault(key if key != "." else os.path.basename(root), []).append(s)
    return projects


def scan_codex(root):
    out = []
    for f in sorted(glob.glob(os.path.join(root, "**", "*.jsonl"), recursive=True)):
        meta = prompt = None
        try:
            with open(f, encoding="utf-8", errors="replace") as fh:
                for raw in fh:
                    try:
                        line = json.loads(raw)
                    except ValueError:
                        continue
                    p = line.get("payload") if isinstance(line.get("payload"), dict) else {}
                    if line.get("type") == "session_meta" and meta is None:
                        meta = {"date": local_day(p.get("timestamp") or line.get("timestamp")),
                                "cwd": p.get("cwd", ""), "id": p.get("id", "")[:8]}
                    elif line.get("type") == "event_msg" and p.get("type") == "user_message":
                        prompt = re.sub(r"\s+", " ", str(p.get("message", "")).strip())[:120]
                        break
        except OSError:
            continue
        if meta is None:
            out.append({"date": "", "cwd": "", "id": "", "prompt": "",
                        "error": "format not understood, see %s" % f})
            continue
        meta["prompt"] = prompt or ""
        out.append(meta)
    return out


def filter_since(projects, since):
    if not since:
        return projects
    out = {}
    for k, rows in projects.items():
        kept = [r for r in rows if r["last"] >= since]
        if kept:
            out[k] = kept
    return out


def digest(label, projects):
    print("# %s" % label)
    if not projects:
        print("(no sessions)\n")
        return
    for key in sorted(projects):
        rows = sorted(projects[key], key=lambda r: (r["last"], r["first"]), reverse=True)
        print("\n== %s: %d session(s), %s..%s, %d user turns" % (
            key, len(rows), min(r["first"] for r in rows), max(r["last"] for r in rows),
            sum(r["turns"] for r in rows)))
        for r in rows:
            print("%s  %s..%s  turns=%-3d %s" % (r["id"], r["first"], r["last"], r["turns"], r["title"]))
            if r["prompt"]:
                print("          > %s" % r["prompt"])
    print()


def main(argv):
    if lifecfg.demo():
        print("sessions: NOT ESTABLISHED, demo folder: this Mac's sessions are not read")
        return 0
    since = None
    args = argv[1:]
    if "--since" in args:
        i = args.index("--since")
        since = args[i + 1] if i + 1 < len(args) else None
        if not since or not re.match(r"^\d{4}-\d{2}-\d{2}$", since):
            print("usage: bin/sessions [--since YYYY-MM-DD] [--codex] [--json]",
                  file=sys.stderr)
            return 2
        del args[i:i + 2]
    want_json = "--json" in args

    result = {"since": since, "host": os.uname().nodename}
    if not os.path.isdir(CLAUDE_ROOT):
        print("no %s" % CLAUDE_ROOT, file=sys.stderr)
        return 2
    result["claude"] = filter_since(scan_root(CLAUDE_ROOT, os.path.join("*", "*.jsonl")), since)

    if "--codex" in args:
        if os.path.isdir(CODEX_ROOT):
            rows = scan_codex(CODEX_ROOT)
            result["codex"] = [r for r in rows if not since or r.get("error") or r["date"] >= since]
        else:
            result["codex_error"] = "no %s" % CODEX_ROOT
    if want_json:
        json.dump(result, sys.stdout, indent=1)
        print()
        return 0

    digest("Claude Code on %s%s" % (result["host"], " since %s" % since if since else ""), result["claude"])
    if "codex" in result:
        rows = result["codex"]
        print("# Codex: %d session(s)" % len(rows))
        for r in sorted(rows, key=lambda r: r["date"], reverse=True):
            if r.get("error"):
                print("codex: %s" % r["error"])
            else:
                print("%s  %s  %s" % (r["date"], r["cwd"], r["id"]))
                if r["prompt"]:
                    print("          > %s" % r["prompt"])
        print()
    if "codex_error" in result:
        print("# Codex\n%s\n" % result["codex_error"])
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv))
