#!/usr/bin/env bash
# requires modern bash; version 3.2 from macOS
# is not good enough, run  brew install bash  to get
# a up-to-date bash environment

SESSIONS_DIR="$HOME/.claude/projects"

# numbered menu; returns 0-based index
pick() {
  local prompt="$1"; shift; local -a items=("$@")
  echo "$prompt" >&2
  for i in "${!items[@]}"; do
    printf "  %d) %s\n" $((i+1)) "${items[$i]}" >&2
  done
  local n
  while true; do
    read -rp "> " n || exit 1
    [[ "$n" =~ ^[0-9]+$ ]] \
      && [ "$n" -ge 1 ] && [ "$n" -le "${#items[@]}" ] \
      && break
    echo "Pick 1–${#items[@]}" >&2
  done
  echo $((n-1))
}

# extract first user message from a session file
first_user_msg() {
  jq -r 'select(.type=="user")
    | .message.content
    | if type=="string" then . else empty end' \
    "$1" 2>/dev/null | head -1
}

# select project
mapfile -t dirs < <(ls -1 "$SESSIONS_DIR")
[ ${#dirs[@]} -eq 0 ] \
  && { echo "No projects in $SESSIONS_DIR"; exit 1; }

proj_idx=$(pick "Project:" "${dirs[@]}")
project_dir="$SESSIONS_DIR/${dirs[$proj_idx]}"

# select session (newest first, with date + hint)
mapfile -t files < <(
  ls -1t "$project_dir"/*.jsonl 2>/dev/null | xargs -I{} basename {}
)
[ ${#files[@]} -eq 0 ] \
  && { echo "No sessions in $project_dir"; exit 1; }

hints=()
for f in "${files[@]}"; do
  ts=$(date -r "$project_dir/$f" "+%Y-%m-%d %H:%M" 2>/dev/null \
    || stat -c "%y" "$project_dir/$f" | cut -c1-16)
  first=$(first_user_msg "$project_dir/$f" | cut -c1-55)
  hints+=("$ts  ${first:-???}")
done

idx=$(pick "Session:" "${hints[@]}")
session_file="$project_dir/${files[$idx]}"

# Propose filename: date + last two dirs of project
ts=$(date -r "$session_file" "+%Y-%m-%d" 2>/dev/null \
  || stat -c "%y" "$session_file" | cut -c1-10)
# dir name is hyphen-separated path; grab last two segments
dir_slug=$(echo "${dirs[$proj_idx]}" \
  | rev | cut -d'-' -f1-2 | rev \
  | tr '[:upper:]' '[:lower:]')
suggested="${ts}-${dir_slug}.md"

read -rp "Filename [$suggested]: " outfile
outfile="${outfile:-$suggested}"

# export: user prompts + claude text only
jq -r '
  select(.type == "user" or .type == "assistant")
  | if .type == "user" then
      (.message.content
        | if type == "string" then "## You:\n" + . else empty end)
    else
      (.message.content[]?
        | select(.type == "text")
        | "## Claude:\n" + .text)
    end
' "$session_file" > "$outfile"

echo "Saved → $outfile ($(wc -l < "$outfile") lines)"
