#!/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

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.

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 fcntl
import json
import locale
import os
import sys
import textwrap

NO_ID = {"", "unknown", "unbekannt"}
LOCK = "/tmp/session-index.lock"  # shared with the SessionEnd 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)
    return len(lines) - len(keep)


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 ...]")
    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("terms", nargs="*", metavar="TERM")
    args = ap.parse_args()

    path = index_path()
    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)
