#!/usr/bin/env bash
#clear
#export PS4='\e[90m+${LINENO} in ${#BASH_SOURCE[@]}>${FUNCNAME[0]}:${BASH_SOURCE[@]##*/} \e[0m'
#set -x

#echo "starting: $0 <LOG_LEVEL=$1>"

### new.method

# ============================================================================
# claudeCode - Claude Code wrapper for oosh
# Makes Claude Code CLI flags easy to use with intuitive method names
# ============================================================================

# Path to claude binary - no need to have it in PATH
CLAUDE_CMD="$HOME/.local/bin/claude"

claudeCode.sessions() # # list all available sessions (interactive picker)
{
  "$CLAUDE_CMD" --resume
}

claudeCode.list() # # alias for sessions - shows session picker
{
  claudeCode.sessions "$@"
}

claudeCode.join() # <session> # resume a specific session by name or ID
{
  local session="$1"
  if [ -n "$session" ]; then
    shift
    "$CLAUDE_CMD" --resume "$session" "$@"
  else
    # No session specified, show picker
    "$CLAUDE_CMD" --resume
  fi
}
claudeCode.join.completion.session() {
  # Could potentially parse ~/.claude/sessions but for now just suggest picker
  echo ";"
}

claudeCode.continue() # # continue the most recent session without picker
{
  "$CLAUDE_CMD" --continue "$@"
}

claudeCode.c() # # shorthand for continue
{
  claudeCode.continue "$@"
}

claudeCode.new() # <?prompt> # start a fresh conversation with optional initial prompt
{
  if [ -n "$1" ]; then
    "$CLAUDE_CMD" --print "$@"
  else
    "$CLAUDE_CMD"
  fi
}

claudeCode.print() # <prompt> # non-interactive: print response and exit
{
  "$CLAUDE_CMD" --print "$@"
}

claudeCode.p() # <prompt> # shorthand for print
{
  claudeCode.print "$@"
}

claudeCode.dangerously() # <prompt> # skip all permission prompts (use with caution!)
{
  "$CLAUDE_CMD" --dangerously-skip-permissions "$@"
}

claudeCode.yolo() # <prompt> # alias for dangerously - skip permissions
{
  claudeCode.dangerously "$@"
}

claudeCode.verbose() # <?prompt> # run with verbose output
{
  "$CLAUDE_CMD" --verbose "$@"
}

claudeCode.model() # <model> <?prompt> # use specific model (sonnet, opus, haiku)
{
  local model="$1"
  if [ -n "$model" ]; then
    shift
    "$CLAUDE_CMD" --model "$model" "$@"
  else
    error.log "usage: cc model <sonnet|opus|haiku> [prompt]"
    return 1
  fi
}
claudeCode.model.completion.model() {
  echo "sonnet"
  echo "opus"
  echo "haiku"
}

claudeCode.opus() # <?prompt> # use opus model
{
  "$CLAUDE_CMD" --model opus "$@"
}

claudeCode.sonnet() # <?prompt> # use sonnet model
{
  "$CLAUDE_CMD" --model sonnet "$@"
}

claudeCode.haiku() # <?prompt> # use haiku model
{
  "$CLAUDE_CMD" --model haiku "$@"
}

claudeCode.chat() # <?prompt> # interactive chat mode (default)
{
  "$CLAUDE_CMD" "$@"
}

claudeCode.help() # # show claude help
{
  "$CLAUDE_CMD" --help
}

claudeCode.version() # # show claude version
{
  "$CLAUDE_CMD" --version
}

claudeCode.v() # # shorthand for version
{
  claudeCode.version
}

claudeCode.config() # # open claude settings/config
{
  "$CLAUDE_CMD" config
}

claudeCode.doctor() # # run claude doctor to check setup
{
  "$CLAUDE_CMD" doctor
}

claudeCode.mcp() # # manage MCP servers
{
  "$CLAUDE_CMD" mcp "$@"
}

claudeCode.allowedTools() # <tools> # restrict to specific tools (comma-separated)
{
  local tools="$1"
  if [ -n "$tools" ]; then
    shift
    "$CLAUDE_CMD" --allowedTools "$tools" "$@"
  else
    error.log "usage: cc allowedTools <tool1,tool2,...> [prompt]"
    return 1
  fi
}

claudeCode.disallowedTools() # <tools> # block specific tools (comma-separated)
{
  local tools="$1"
  if [ -n "$tools" ]; then
    shift
    "$CLAUDE_CMD" --disallowedTools "$tools" "$@"
  else
    error.log "usage: cc disallowedTools <tool1,tool2,...> [prompt]"
    return 1
  fi
}

claudeCode.maxTurns() # <turns> <?prompt> # limit conversation turns
{
  local turns="$1"
  if [ -n "$turns" ]; then
    shift
    "$CLAUDE_CMD" --max-turns "$turns" "$@"
  else
    error.log "usage: cc maxTurns <number> [prompt]"
    return 1
  fi
}

claudeCode.systemPrompt() # <prompt> <?message> # set custom system prompt
{
  local sysprompt="$1"
  if [ -n "$sysprompt" ]; then
    shift
    "$CLAUDE_CMD" --system-prompt "$sysprompt" "$@"
  else
    error.log "usage: cc systemPrompt <prompt> [message]"
    return 1
  fi
}

claudeCode.appendSystemPrompt() # <prompt> <?message> # append to system prompt
{
  local sysprompt="$1"
  if [ -n "$sysprompt" ]; then
    shift
    "$CLAUDE_CMD" --append-system-prompt "$sysprompt" "$@"
  else
    error.log "usage: cc appendSystemPrompt <prompt> [message]"
    return 1
  fi
}

claudeCode.output() # <format> <?prompt> # set output format (text, json, stream-json)
{
  local format="$1"
  if [ -n "$format" ]; then
    shift
    "$CLAUDE_CMD" --output-format "$format" "$@"
  else
    error.log "usage: cc output <text|json|stream-json> [prompt]"
    return 1
  fi
}
claudeCode.output.completion.format() {
  echo "text"
  echo "json"
  echo "stream-json"
}

claudeCode.json() # <?prompt> # output as JSON
{
  "$CLAUDE_CMD" --output-format json "$@"
}

claudeCode.pipe() # # read from stdin (for piping)
{
  "$CLAUDE_CMD" -p "$@"
}

claudeCode.init() # <?path> # initialize claude in a directory
{
  if [ -n "$1" ]; then
    "$CLAUDE_CMD" init "$1"
  else
    "$CLAUDE_CMD" init
  fi
}

claudeCode.update() # # update claude code
{
  "$CLAUDE_CMD" update
}

claudeCode.login() # # login to claude
{
  "$CLAUDE_CMD" login
}

claudeCode.logout() # # logout from claude
{
  "$CLAUDE_CMD" logout
}

claudeCode.install() # # install claude code from web for linux
{
  local INSTALL_DIR="${HOME}/.local/bin"
  local CONFIG_FILE="${CONFIG:-$HOME/config/user.env}"

  # Check if already installed
  if command -v claude &> /dev/null; then
    info.log "Claude Code is already installed: $(which claude)"
    "$CLAUDE_CMD" --version
    echo ""
    read -p "Reinstall/update anyway? [y/N] " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
      info.log "Installation cancelled"
      return 0
    fi
  fi

  info.log "Installing Claude Code for Linux..."

  # Check for curl
  if ! command -v curl &> /dev/null; then
    error.log "curl is required but not installed. Please install curl first."
    return 1
  fi

  # Download and run the official installer
  info.log "Downloading and running official installer..."
  curl -fsSL https://claude.ai/install.sh | sh

  if [ $? -ne 0 ]; then
    error.log "Installation failed"
    return 1
  fi

  # Check if ~/.local/bin is in PATH via config
  if [ -f "$CONFIG_FILE" ]; then
    if ! grep -q '\.local/bin' "$CONFIG_FILE"; then
      info.log "Adding ~/.local/bin to PATH in config..."
      # Read current PATH from config
      local current_path=$(grep '^export PATH=' "$CONFIG_FILE" | head -1)
      if [ -n "$current_path" ]; then
        # Check if .local/bin is already in the PATH value
        if ! echo "$current_path" | grep -q '\.local/bin'; then
          # Append to existing PATH
          sed -i 's|^export PATH="\(.*\)"$|export PATH="\1:'"$HOME"'/.local/bin"|' "$CONFIG_FILE"
          info.log "Updated PATH in $CONFIG_FILE"
        fi
      else
        # Add new PATH export
        echo "export PATH=\"\$PATH:$HOME/.local/bin\"" >> "$CONFIG_FILE"
        info.log "Added PATH to $CONFIG_FILE"
      fi
    else
      info.log "~/.local/bin already in config PATH"
    fi
  else
    warn.log "Config file not found at $CONFIG_FILE"
    warn.log "Add ~/.local/bin to your PATH manually if needed"
  fi

  # Add to current session PATH if not present
  if [[ ":$PATH:" != *":$INSTALL_DIR:"* ]]; then
    export PATH="$PATH:$INSTALL_DIR"
    info.log "Added $INSTALL_DIR to current session PATH"
  fi

  # Verify installation
  if command -v claude &> /dev/null; then
    success.log "Claude Code installed successfully!"
    "$CLAUDE_CMD" --version
    echo ""
    info.log "Run 'claudeCode login' to authenticate"
  else
    error.log "Installation completed but 'claude' command not found"
    error.log "You may need to restart your shell or add ~/.local/bin to PATH"
    return 1
  fi
}

claudeCode.uninstall() # # uninstall claude code
{
  local INSTALL_DIR="${HOME}/.local"
  local CLAUDE_DIR="${INSTALL_DIR}/share/claude"
  local CLAUDE_BIN="${INSTALL_DIR}/bin/claude"

  if [ ! -f "$CLAUDE_BIN" ] && [ ! -d "$CLAUDE_DIR" ]; then
    warn.log "Claude Code does not appear to be installed"
    return 0
  fi

  echo "This will remove:"
  [ -f "$CLAUDE_BIN" ] && echo "  - $CLAUDE_BIN"
  [ -d "$CLAUDE_DIR" ] && echo "  - $CLAUDE_DIR"
  echo ""
  read -p "Are you sure you want to uninstall Claude Code? [y/N] " -n 1 -r
  echo

  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    info.log "Uninstall cancelled"
    return 0
  fi

  info.log "Removing Claude Code..."

  # Remove symlink/binary
  if [ -f "$CLAUDE_BIN" ] || [ -L "$CLAUDE_BIN" ]; then
    rm -f "$CLAUDE_BIN"
    info.log "Removed $CLAUDE_BIN"
  fi

  # Remove installation directory
  if [ -d "$CLAUDE_DIR" ]; then
    rm -rf "$CLAUDE_DIR"
    info.log "Removed $CLAUDE_DIR"
  fi

  success.log "Claude Code uninstalled successfully"
  info.log "Note: ~/.claude config directory was preserved"
}

claudeCode.status() # # show current claude status
{
  "$CLAUDE_CMD" status
  echo ""
  echo "Claude Code wrapper for oosh"
  echo "Type 'claudeCode' for interactive mode"
  echo "Type 'claudeCode help' for all options"
}

claudeCode.usage()
{
  local this=${0##*/}
  echo "You started"
  echo "$0

  claudeCode - Claude Code wrapper for oosh
  Makes cryptic --flags easy to remember!

  Usage:
  $this: command     Description
  ─────────────────────────────────────────────────────
  SESSION MANAGEMENT:
      list          show session picker (--resume)
      join <name>   resume specific session (--resume <name>)
      continue      continue most recent session (--continue)
      c             shorthand for continue
      new           start fresh conversation

  OUTPUT MODES:
      print <msg>   non-interactive output (--print)
      p <msg>       shorthand for print
      json <msg>    output as JSON
      pipe          read from stdin (-p)

  MODELS:
      opus <msg>    use opus model
      sonnet <msg>  use sonnet model
      haiku <msg>   use haiku model
      model <m>     specify model (--model)

  PERMISSIONS:
      yolo <msg>    skip all prompts (--dangerously-skip-permissions)
      dangerously   same as yolo

  CONFIGURATION:
      config        open settings
      doctor        check setup
      init          initialize directory
      mcp           manage MCP servers

  INSTALLATION:
      install       install claude code from web for linux
      uninstall     remove claude code installation
      update        update claude code to latest version
      login         authenticate with claude
      logout        log out from claude

  OTHER:
      verbose       verbose output
      maxTurns <n>  limit turns
      help          show claude --help
      v             show version
  ─────────────────────────────────────────────────────

  Examples:
    $this list                    # pick a session to resume
    $this continue                # continue last session
    $this join my-feature         # resume 'my-feature' session
    $this opus 'explain this'     # use opus model
    $this print 'quick question'  # get answer and exit
    $this yolo 'fix all tests'    # no permission prompts
    cat file.py | $this pipe 'review this'
  "
}

claudeCode.start()
{
  #echo "sourcing init"
  source this

  if [ -z "$1" ]; then
    # No arguments - start interactive claude
    "$CLAUDE_CMD"
    return 0
  fi

  this.start "$@"
}

claudeCode.start "$@"
