#!/bin/bash

# Resolve the real directory even if this script is symlinked
SOURCE="${BASH_SOURCE[0]}"
while [ -h "$SOURCE" ]; do
  DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"
  SOURCE="$(readlink "$SOURCE")"
  [[ $SOURCE != /* ]] && SOURCE="$DIR/$SOURCE"
done
SCRIPT_DIR="$(cd -P "$(dirname "$SOURCE")" && pwd)"

# Main CLI entry point with subcommands
COMMAND="$1"
shift

case "$COMMAND" in
  index)
    # Route to index-conversations script with remaining args
    "$SCRIPT_DIR/index-conversations" "$@"
    ;;

  search)
    # Route to search implementation
    npx tsx "$SCRIPT_DIR/../src/search-cli.ts" "$@"
    ;;

  show)
    # Route to show implementation
    npx tsx "$SCRIPT_DIR/../src/show-cli.ts" "$@"
    ;;

  stats)
    # Route to stats implementation
    npx tsx "$SCRIPT_DIR/../src/stats-cli.ts" "$@"
    ;;

  sync)
    # Route to sync implementation
    npx tsx "$SCRIPT_DIR/../src/sync-cli.ts" "$@"
    ;;

  --help|-h|"")
    cat <<'EOF'
episodic-memory - Manage and search Claude Code conversations

USAGE:
  episodic-memory <command> [options]

COMMANDS:
  sync        Sync conversations from ~/.claude/projects and index them
  index       Index conversations for search
  search      Search indexed conversations
  show        Display a conversation in readable format
  stats       Show index statistics

Run 'episodic-memory <command> --help' for command-specific help.

EXAMPLES:
  # Index all conversations
  episodic-memory index --cleanup

  # Search for something
  episodic-memory search "React Router auth"

  # Display a conversation
  episodic-memory show path/to/conversation.jsonl

  # Generate HTML output
  episodic-memory show --format html conversation.jsonl > output.html
EOF
    ;;

  *)
    echo "Unknown command: $COMMAND"
    echo "Try: episodic-memory --help"
    exit 1
    ;;
esac
