#!/usr/bin/env python3
"""Search the global Claude Code session index and resume a session.

The index is written by the /exit skill and the SessionEnd hook session-index.sh.

  sessions                  pick from all sessions interactively
  sessions TERM...          only sessions matching all terms (case-insensitive), searched in
                            the index line and in the session's detailed log file
  sessions -l TERM...       print the matches as a list instead (default when not on a terminal)
  sessions -r N TERM...     resume match number N directly
  sessions -n COUNT ...     at most COUNT matches (list default 20, 0 = all)
  sessions -a ...           every matching line; by default a session that was closed
                            several times is shown once, with its newest line
  sessions --import         add all sessions Claude Code still has transcripts of, but that
                            are not in the index yet, as lines without a summary (like the
                            hook writes); the index is backed up first
  sessions --import --dry-run   only show what --import would add

Keys: Up/Down, PgUp/PgDn, Pos1/End move; Enter resumes the selected session in its
project directory; d removes the selected session's lines from the index (after asking;
its session log file is kept); Esc or x exits.

Sessions removed with d or closed with /discard are recorded in
~/.claude/session-index-excluded, so that --import does not bring them back.

Index path: $CLAUDE_SESSION_INDEX, otherwise the same variable from the `env` section of
~/.claude/settings.json, otherwise ~/.claude/Sessions.md.
"""

import argparse
import curses
import datetime
import fcntl
import glob
import json
import locale
import os
import shutil
import sys
import textwrap

VERSION = "2.0"  # claude-session-log package version; make-zip.sh checks it against VERSION
NO_ID = {"", "unknown", "unbekannt"}
LOCK = "/tmp/session-index.lock"  # shared with the SessionEnd hook
CLAUDE_DIR = os.path.expanduser("~/.claude")
EXCLUDED = os.path.join(CLAUDE_DIR, "session-index-excluded")  # shared with the hook


def index_path():
    path = os.environ.get("CLAUDE_SESSION_INDEX")
    if not path:
        # Outside Claude Code the variable is usually only set in settings.json.
        try:
            with open(os.path.expanduser("~/.claude/settings.json"), encoding="utf-8") as f:
                path = (json.load(f).get("env") or {}).get("CLAUDE_SESSION_INDEX")
        except (OSError, ValueError):
            path = None
    return path or os.path.expanduser("~/.claude/Sessions.md")


def read_index(path):
    """Yields one dict per index line, newest first (the file's own order)."""
    with open(path, encoding="utf-8", errors="replace", newline="") as f:
        for raw in f:
            line = raw.rstrip("\r\n")
            if not line.startswith("- "):
                continue
            # Fields: date | directory | name | summary | session ID | session file
            parts = line[2:].split(" | ")
            if len(parts) > 6:
                parts = parts[:3] + [" | ".join(parts[3:-2])] + parts[-2:]
            parts += [""] * (6 - len(parts))
            date, directory, name, summary, sid, logfile = (p.strip() for p in parts)
            if logfile == "-":
                logfile = ""
            yield {"line": line, "date": date, "dir": directory, "name": name,
                   "summary": summary, "id": sid, "file": logfile}


def find(path, terms, show_all, limit):
    terms = [t.lower() for t in terms]
    file_text = {}

    def text_of(name):
        if name not in file_text:
            try:
                with open(name, encoding="utf-8", errors="replace") as f:
                    file_text[name] = f.read().lower()
            except OSError:
                file_text[name] = ""
        return file_text[name]

    seen, found = set(), []
    for e in read_index(path):
        key = "" if e["id"] in NO_ID else e["id"]
        if not show_all and key and key in seen:
            continue
        line = e["line"].lower()
        if not all(t in line or (e["file"] and t in text_of(e["file"])) for t in terms):
            continue
        if key:
            seen.add(key)
        found.append(e)
        if limit and len(found) >= limit:
            break
    return found


def belongs(line, e):
    """True if an index line belongs to the session of entry e (by ID, or the line itself)."""
    if not line.startswith("- "):
        return False
    if e["id"] in NO_ID:
        return line == e["line"]
    return f"| {e['id']} |" in line


def count_lines(path, e):
    with open(path, encoding="utf-8", errors="replace", newline="") as f:
        return sum(belongs(raw.rstrip("\r\n"), e) for raw in f)


def remove_session(path, e):
    """Removes all index lines of e's session, keeping everything else byte for byte.
    Returns the number of lines removed."""
    with open(LOCK, "a") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        with open(path, encoding="utf-8", errors="surrogateescape", newline="") as f:
            lines = f.readlines()
        keep = [raw for raw in lines if not belongs(raw.rstrip("\r\n"), e)]
        if len(keep) != len(lines):
            with open(path, "w", encoding="utf-8", errors="surrogateescape", newline="") as f:
                f.writelines(keep)
    if e["id"] not in NO_ID:
        exclude(e["id"])
    return len(lines) - len(keep)


def exclude(sid):
    """Records a session ID so that --import does not add it again."""
    try:
        os.makedirs(CLAUDE_DIR, exist_ok=True)
        with open(EXCLUDED, "a", encoding="utf-8") as f:
            f.write(sid + "\n")
    except OSError:
        pass


# ---------------------------------------------------------------- import

TEXTS = {
    "en": {"nosum": "no summary", "title": "Title", "first": "First input",
           "cont": "continued in session", "head": "# Sessions",
           "hint": "Newest first. To resume a session: change to the project directory, "
                   "then `claude --resume <session ID>`."},
    "de": {"nosum": "ohne Zusammenfassung", "title": "Titel", "first": "Erste Eingabe",
           "cont": "fortgesetzt in Sitzung", "head": "# Sitzungen",
           "hint": "Neueste oben. Sitzung fortsetzen: ins Projektverzeichnis wechseln, "
                   "dann `claude --resume <Session-ID>`."},
}


def language(cwd):
    """Same rule as the hook: the first `language` setting found, German if it names German."""
    for name in (os.path.join(cwd or "", ".claude", "settings.local.json"),
                 os.path.join(cwd or "", ".claude", "settings.json"),
                 os.path.join(CLAUDE_DIR, "settings.json")):
        try:
            with open(name, encoding="utf-8") as f:
                lang = (json.load(f).get("language") or "").strip().lower()
        except (OSError, ValueError, AttributeError):
            continue
        if lang:
            return "de" if lang.startswith(("german", "deutsch")) or lang == "de" \
                or lang.startswith(("de-", "de_")) else "en"
    return "en"


def clean(text, limit=150):
    return " ".join(text.replace("|", " ").split())[:limit]


def scan_transcript(path):
    """Reads what the index line needs from one transcript; None if the session had no input."""
    custom = ai = first = cwd = last_ts = cont = None
    with open(path, encoding="utf-8", errors="replace") as f:
        for raw in f:
            try:
                e = json.loads(raw)
            except ValueError:
                continue
            if not isinstance(e, dict):
                continue
            t = e.get("type")
            if e.get("timestamp"):
                last_ts = e["timestamp"]
            if e.get("cwd"):
                cwd = e["cwd"]
            if t == "relocated" and e.get("relocatedCwd"):
                cwd = e["relocatedCwd"]
            elif t == "custom-title":
                custom = e.get("customTitle") or custom
            elif t == "ai-title":
                ai = e.get("aiTitle") or ai
            elif t == "continued-in":
                cont = e.get("continuedInSessionId") or cont
            elif first is None and t == "user" and not e.get("isMeta"):
                content = (e.get("message") or {}).get("content")
                if isinstance(content, str) and not content.startswith("<"):
                    first = content
    if not first:
        return None
    try:
        when = datetime.datetime.fromisoformat(last_ts.replace("Z", "+00:00")).astimezone()
    except (AttributeError, ValueError):
        when = datetime.datetime.fromtimestamp(os.path.getmtime(path))
    return {"custom": custom, "ai": ai, "first": first, "cwd": cwd or "", "cont": cont,
            "date": when.strftime("%Y-%m-%d %H:%M")}


def import_sessions(path, dry_run):
    ids_in_index = set()
    if os.path.isfile(path):
        ids_in_index = {e["id"] for e in read_index(path)}
    try:
        with open(EXCLUDED, encoding="utf-8") as f:
            excluded = {l.strip() for l in f if l.strip()}
    except OSError:
        excluded = set()

    new, counts = [], {"in index": 0, "excluded": 0, "no input": 0, "unreadable": 0}
    files = sorted(glob.glob(os.path.join(CLAUDE_DIR, "projects", "*", "*.jsonl")))
    for n, tf in enumerate(files, 1):
        if sys.stderr.isatty():
            print(f"\rReading transcripts: {n}/{len(files)}", end="", file=sys.stderr, flush=True)
        sid = os.path.basename(tf)[:-len(".jsonl")]
        if sid in ids_in_index:
            counts["in index"] += 1
            continue
        if sid in excluded:
            counts["excluded"] += 1
            continue
        try:
            s = scan_transcript(tf)
        except OSError:
            counts["unreadable"] += 1
            continue
        if not s:
            counts["no input"] += 1
            continue
        tx = TEXTS[language(s["cwd"])]
        summary = tx["nosum"]
        if s["ai"]:
            summary += f" - {tx['title']}: {clean(s['ai'])}"
        summary += f" - {tx['first']}: {clean(s['first'])}"
        if s["cont"]:
            summary += f" - {tx['cont']} {s['cont']}"
        name = clean(s["custom"] or s["ai"] or sid, 80)
        new.append((s["date"], f"- {s['date']} | {s['cwd']} | {name} | {summary} | {sid} | -"))
    if sys.stderr.isatty():
        print(file=sys.stderr)

    new.sort(reverse=True)
    for _, line in new:
        print(line if len(line) <= 160 else line[:157] + "...")
    skipped = ", ".join(f"{v} {k}" for k, v in counts.items() if v)
    print(f"\n{len(new)} session(s) {'would be ' if dry_run else ''}added"
          + (f"; skipped: {skipped}" if skipped else "") + ".")
    if dry_run or not new:
        return

    with open(LOCK, "a") as lock:
        fcntl.flock(lock, fcntl.LOCK_EX)
        if os.path.isfile(path):
            with open(path, encoding="utf-8", errors="surrogateescape", newline="") as f:
                lines = f.readlines()
            stamp = datetime.datetime.now().strftime("%Y%m%d-%H%M%S")
            shutil.copyfile(path, f"{path}.bak-{stamp}")
            print(f"Backup: {path}.bak-{stamp}")
        else:
            tx = TEXTS[language("")]
            lines = [tx["head"] + "\r\n", "\r\n", tx["hint"] + "\r\n", "\r\n"]
        # Keep the existing lines in their order and put each new line before the first
        # existing line that is older, so the index stays newest first.
        out, queue = [], [l for _, l in new]
        for raw in lines:
            if raw.startswith("- "):
                date = raw[2:18]
                while queue and queue[0][2:18] > date:
                    out.append(queue.pop(0) + "\r\n")
            out.append(raw)
        if out and not out[-1].endswith("\n"):
            out[-1] += "\r\n"
        out.extend(l + "\r\n" for l in queue)
        os.makedirs(os.path.dirname(path) or ".", exist_ok=True)
        with open(path, "w", encoding="utf-8", errors="surrogateescape", newline="") as f:
            f.writelines(out)
    print(f"Index: {path}")


def resume(e):
    """Replaces this process with `claude --resume`; returns an error text if it cannot."""
    if e["id"] in NO_ID:
        return "this session has no session ID"
    try:
        os.chdir(e["dir"])
    except OSError:
        return f"directory not found: {e['dir']}"
    print(f"Resuming {e['name']} in {e['dir']}", flush=True)
    try:
        os.execvp("claude", ["claude", "--resume", e["id"]])
    except OSError as err:
        return f"cannot start claude: {err}"


def segments(text, terms):
    """Splits text into (part, is_match) pieces; matches are case-insensitive, overlaps merged."""
    low, spans = text.lower(), []
    for t in terms:
        t = t.lower()
        start = low.find(t) if t else -1
        while start >= 0:
            spans.append((start, start + len(t)))
            start = low.find(t, start + 1)
    merged = []
    for s, e in sorted(spans):
        if merged and s <= merged[-1][1]:
            merged[-1][1] = max(merged[-1][1], e)
        else:
            merged.append([s, e])
    out, pos = [], 0
    for s, e in merged:
        if s > pos:
            out.append((text[pos:s], False))
        out.append((text[s:e], True))
        pos = e
    if pos < len(text):
        out.append((text[pos:], False))
    return out


def print_list(found, terms):
    tty = sys.stdout.isatty()
    b, d, y, r = ("\033[1m", "\033[2m", "\033[1;93m", "\033[0m") if tty else ("", "", "", "")

    def hl(text, base=""):
        # Highlight in bright yellow, then return to the surrounding style.
        return base + "".join(f"{r}{y}{p}{r}{base}" if hit else p
                              for p, hit in segments(text, terms)) + (r if base else "")

    for n, e in enumerate(found, 1):
        print(f"{b}{n:3d}{r}  {hl(e['date'])}  {hl(e['name'], b)}  {hl(e['dir'])}")
        print(f"     {hl(e['summary'])}")
        if e["file"]:
            print(f"     {hl(e['file'], d)}")
        print(f"     {hl('claude --resume ' + e['id'], d)}")


# ---------------------------------------------------------------- interactive picker

HOME_SEQ = {"[1~", "[7~", "[H", "OH"}
END_SEQ = {"[4~", "[8~", "[F", "OF"}
UP_SEQ, DOWN_SEQ = {"[A", "OA"}, {"[B", "OB"}
PGUP_SEQ, PGDN_SEQ = {"[5~"}, {"[6~"}
HELP = "Up/Down PgUp/PgDn Pos1/End  Enter resume  d delete  Esc/x quit"


def put(win, y, x, text, attr=0):
    """addnstr that clips to the window and ignores the bottom-right-corner error."""
    h, w = win.getmaxyx()
    if 0 <= y < h and x < w:
        try:
            win.addnstr(y, x, text, w - x, attr)
        except curses.error:
            pass


def put_hl(win, y, x, text, attr, terms, hit_attr):
    """Like put, with the search terms drawn in hit_attr."""
    w = win.getmaxyx()[1]
    for part, hit in segments(text, terms):
        if x >= w:
            break
        put(win, y, x, part, hit_attr | (attr & curses.A_REVERSE) if hit else attr)
        x += len(part)


def read_key(win):
    """Returns 'up', 'down', 'pgup', 'pgdn', 'home', 'end', 'enter', 'delete', 'quit',
    'resize' or None."""
    try:
        k = win.get_wch()
    except curses.error:
        return None
    named = {curses.KEY_UP: "up", curses.KEY_DOWN: "down",
             curses.KEY_PPAGE: "pgup", curses.KEY_NPAGE: "pgdn",
             curses.KEY_HOME: "home", curses.KEY_FIND: "home", curses.KEY_A1: "home",
             curses.KEY_END: "end", curses.KEY_SELECT: "end", curses.KEY_C1: "end",
             curses.KEY_ENTER: "enter", curses.KEY_RESIZE: "resize"}
    if isinstance(k, int):
        return named.get(k)
    if k in ("\n", "\r"):
        return "enter"
    if k in ("x", "X"):
        return "quit"
    if k in ("d", "D"):
        return "delete"
    if k == "\x1b":
        # A lone Esc quits. If more bytes follow at once, it was a key sequence that the
        # terminal description did not know; decode the common ones here.
        win.nodelay(True)
        seq = ""
        try:
            while len(seq) < 6:
                c = win.get_wch()
                seq += c if isinstance(c, str) else ""
        except curses.error:
            pass
        finally:
            win.nodelay(False)
        if not seq:
            return "quit"
        for keys, name in ((HOME_SEQ, "home"), (END_SEQ, "end"), (UP_SEQ, "up"),
                           (DOWN_SEQ, "down"), (PGUP_SEQ, "pgup"), (PGDN_SEQ, "pgdn")):
            if seq in keys:
                return name
    return None


def confirm(win, question):
    """Shows question in the bottom line and returns True for y, False for any other key."""
    h, w = win.getmaxyx()
    put(win, h - 1, 0, f" {question} (y/n) ".ljust(w), curses.A_BOLD | curses.A_REVERSE)
    win.refresh()
    try:
        k = win.get_wch()
    except curses.error:
        return False
    if k == "\x1b":  # swallow the rest of a key sequence, if any
        win.nodelay(True)
        try:
            while True:
                win.get_wch()
        except curses.error:
            pass
        finally:
            win.nodelay(False)
    return k in ("y", "Y")


def pick(stdscr, found, terms, path):
    curses.curs_set(0)
    stdscr.keypad(True)
    # Search terms in bright yellow: colour 11 where the terminal has 16 colours, else bold yellow.
    hit_attr = curses.A_BOLD
    if curses.has_colors():
        curses.start_color()
        try:
            curses.use_default_colors()
            bg = -1
        except curses.error:
            bg = curses.COLOR_BLACK
        curses.init_pair(1, 11 if curses.COLORS >= 16 else curses.COLOR_YELLOW, bg)
        hit_attr |= curses.color_pair(1)
    sel, top, msg = 0, 0, ""
    name_w = min(30, max(len(e["name"]) for e in found))

    while True:
        h, w = stdscr.getmaxyx()
        detail_h = min(8, max(0, h - 4))
        list_h = max(1, h - 1 - detail_h)
        top = min(max(top, sel - list_h + 1), sel)

        stdscr.erase()
        what = f"{len(found)} sessions" + (f" matching: {' '.join(terms)}" if terms else "")
        head = f" {what}   [{sel + 1}/{len(found)}]"
        put(stdscr, 0, 0, head.ljust(w), curses.A_BOLD | curses.A_REVERSE)
        if len(head) + len(HELP) + 3 < w:
            put(stdscr, 0, w - len(HELP) - 1, HELP, curses.A_REVERSE)

        for row in range(list_h):
            i = top + row
            if i >= len(found):
                break
            e = found[i]
            name = e["name"] if len(e["name"]) <= name_w else e["name"][:name_w - 1] + "…"
            text = f" {e['date']}  {name:<{name_w}}  {e['dir']}"
            put_hl(stdscr, 1 + row, 0, text.ljust(w), curses.A_REVERSE if i == sel else 0,
                   terms, hit_attr)

        if detail_h >= 4:
            e = found[sel]
            y = h - detail_h
            put(stdscr, y, 0, "─" * w, curses.A_DIM)
            info = [f" Project: {e['dir']}",
                    f" Log:     {e['file'] or 'none (ended without /exit)'}",
                    f" Resume:  claude --resume {e['id']}"]
            room = detail_h - 1 - len(info)
            text = textwrap.wrap(e["summary"], max(10, w - 2)) or [""]
            if len(text) > room:
                text = text[:room]
                text[-1] = text[-1][:max(0, w - 4)] + " …"
            for n, t in enumerate(text):
                put_hl(stdscr, y + 1 + n, 1, t, curses.A_BOLD, terms, hit_attr)
            for n, t in enumerate(info):
                put_hl(stdscr, h - len(info) + n, 0, t, curses.A_DIM, terms, hit_attr)
            if msg:
                put(stdscr, h - 1, 0, f" {msg} ".ljust(w), curses.A_REVERSE)
        stdscr.refresh()

        key = read_key(stdscr)
        msg = ""
        last = len(found) - 1
        if key == "quit":
            return None
        if key == "enter":
            if found[sel]["id"] in NO_ID:
                msg = "This session has no session ID."
            elif not os.path.isdir(found[sel]["dir"]):
                msg = f"Directory not found: {found[sel]['dir']}"
            else:
                return found[sel]
        elif key == "delete":
            e = found[sel]
            try:
                n = count_lines(path, e)
                if n and confirm(stdscr, f"Remove {e['name']} from the index ({n} line"
                                         f"{'' if n == 1 else 's'}; its log file is kept)?"):
                    removed = remove_session(path, e)
                    found = [f for f in found if not belongs(f["line"], e)]
                    if not found:
                        return None
                    sel = min(sel, len(found) - 1)
                    msg = f"Removed {removed} line{'' if removed == 1 else 's'}."
                elif not n:
                    msg = "This session is no longer in the index."
            except OSError as err:
                msg = f"Cannot change the index: {err}"
        elif key == "up":
            sel = max(0, sel - 1)
        elif key == "down":
            sel = min(last, sel + 1)
        elif key == "pgup":
            sel = max(0, sel - list_h)
        elif key == "pgdn":
            sel = min(last, sel + list_h)
        elif key == "home":
            sel = 0
        elif key == "end":
            sel = last


def main():
    ap = argparse.ArgumentParser(prog="sessions", description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter,
                                 usage="sessions [-l] [-a] [-n COUNT] [-r N] [TERM ...]\n"
                                       "       sessions --import [--dry-run]")
    ap.add_argument("-r", type=int, metavar="N", help="resume match number N")
    ap.add_argument("-n", type=int, metavar="COUNT", help="at most COUNT matches, 0 = all")
    ap.add_argument("-a", action="store_true", help="show every matching line")
    ap.add_argument("-l", action="store_true", help="print a list instead of the picker")
    ap.add_argument("--import", dest="do_import", action="store_true",
                    help="add sessions from stored transcripts that are not in the index")
    ap.add_argument("--dry-run", action="store_true", help="with --import: only show them")
    ap.add_argument("--version", action="version", version=f"claude-session-log {VERSION}")
    ap.add_argument("terms", nargs="*", metavar="TERM")
    args = ap.parse_args()

    path = index_path()
    if args.dry_run and not args.do_import:
        ap.error("--dry-run only works with --import")
    if args.do_import:
        if args.terms or args.r is not None:
            ap.error("--import takes no search terms or -r")
        import_sessions(path, args.dry_run)
        return
    if not os.path.isfile(path):
        sys.exit(f"sessions: no index at {path}")

    interactive = not args.l and args.r is None and sys.stdin.isatty() and sys.stdout.isatty()
    limit = args.n if args.n is not None else (0 if interactive or args.r else 20)
    found = find(path, args.terms, args.a, limit)
    if not found:
        print("No matching sessions.")
        sys.exit(1)

    if args.r is not None:
        if not 1 <= args.r <= len(found):
            sys.exit(f"sessions: no match number {args.r}")
        sys.exit(f"sessions: {resume(found[args.r - 1])}")

    if not interactive:
        print_list(found, args.terms)
        return

    locale.setlocale(locale.LC_ALL, "")
    os.environ.setdefault("ESCDELAY", "25")
    chosen = curses.wrapper(pick, found, args.terms, path)
    if chosen:
        sys.exit(f"sessions: {resume(chosen)}")


if __name__ == "__main__":
    try:
        main()
    except KeyboardInterrupt:
        sys.exit(130)
