#!/bin/bash

###############################################################################
# gw.sh – Git-Worktree helper main entry point
# ---------------------------------------------------------------------------
# This script prints a line like: cd "/abs/path" for your shell wrapper to eval
# so your interactive shell actually changes directories. See wrapper notes
# below. It routes commands to appropriate modules and offers an interactive
# picker when invoked with no args.
###############################################################################

# Recommended wrapper (place in ~/.bash_profile or ~/.zshrc):
#
# gw () {
#   local script="/absolute/path/to/gw.sh"  # UPDATE THIS PATH
#   local out
#   out="$(command bash "$script" "$@")"
#   local status=$?
#   local cd_line
#   cd_line="$(printf '%s\n' "$out" | grep -m1 '^cd \".*\"')"
#   [[ -n $cd_line ]] && eval "$cd_line"
#   printf '%s\n' "$out" | grep -v -F "$cd_line"
#   return $status
# }

# --------------------------- Utilities --------------------------------------
set -o errexit
set -o pipefail
set -o nounset

# Don't exit on errors inside helper subshells we explicitly guard
# lastpipe not available on older macOS bash; ignore

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
source "$SCRIPT_DIR/shell/gw_load.sh"
gw_load_core

# --------------------------- Module Loading ---------------------------------

# Source Git API module first (required by other modules)
if [[ -f "$SCRIPT_DIR/api/git.sh" ]]; then
  source "$SCRIPT_DIR/api/git.sh"
else
  err "api/git.sh not found in $SCRIPT_DIR"
  exit 1
fi

# Source command-line operations
  COMMANDS_DIR="$SCRIPT_DIR/shell"
  for command_file in \
    "git/create_worktree.sh" \
    "git/delete_worktree.sh" \
    "git/list_worktrees.sh" \
    "git/checkout_worktree.sh" \
    "git/status.sh" \
    "env_copy_command.sh" \
    "tmux/new_session_command.sh"
  do
    if [[ -f "$COMMANDS_DIR/$command_file" ]]; then
      # shellcheck source=/dev/null
      source "$COMMANDS_DIR/$command_file"
    else
      err "Missing command implementation: $COMMANDS_DIR/$command_file"
      exit 1
    fi
  done
unset command_file
unset COMMANDS_DIR

# Source tmux API module
if [[ -f "$SCRIPT_DIR/api/tmux.sh" ]]; then
  source "$SCRIPT_DIR/api/tmux.sh"
else
  err "api/tmux.sh not found in $SCRIPT_DIR"
  exit 1
fi

get_current_worktree_title() {
  local branch=""
  local worktree=""

  if command -v git >/dev/null 2>&1 && git rev-parse --git-dir >/dev/null 2>&1; then
    branch="$(git rev-parse --abbrev-ref HEAD 2>/dev/null || echo "")"
    if [[ -n "$branch" && "$branch" != "HEAD" ]]; then
      worktree="$branch"
    else
      worktree="$(git rev-parse --short HEAD 2>/dev/null || echo "")"
    fi
  fi

  if [[ -z "$worktree" ]]; then
    worktree="$(pwd -P)"
    worktree="$(basename "$worktree")"
  fi

  worktree="${worktree//\//-}"
  worktree="${worktree// /-}"

  if [[ -z "$worktree" ]]; then
    worktree="unknown"
  fi

  printf 'orchestra [orchestra/%s]' "$worktree"
}

set_terminal_title() {
  local tty_device
  tty_device="$(tty 2>/dev/null || true)"
  if [[ -z "$tty_device" || ! -w "$tty_device" ]]; then
    return 0
  fi

  local title
  title="$(get_current_worktree_title)"
  printf '\033]0;%s\007' "$title" >"$tty_device" 2>/dev/null || true
}

# Interactive functionality is provided by the Rust TUI (gw-tui)
# No longer sourcing interactive.sh - Rust TUI is the primary interface

# --------------------------- core features ----------------------------------

usage() {
  echo "Usage: $(basename "$0") <command> [args]"
  echo ""
  echo "Git worktree helper - command-line manages worktrees, interactive manages tmux sessions."
  echo ""
  echo "Commands:"
  echo "  (no args)                      Interactive picker of worktrees + tmux sessions"
  echo "  b, create, add <branch>       Create a new branch and its worktree"
  echo "  d, delete, rm <branch>        Delete a worktree and its local branch"
  echo "  ls, list                      List worktrees only"
  echo "  ch, checkout -b <branch>      Create <branch>, its worktree, and switch"
  echo "  ch, checkout <branch>         Switch to the worktree of <branch>"
  echo "  copy-env <worktreename>       Copy env files from current worktree to target"
  echo "  status [git status args]      Show current worktree + git status"
  echo "  upgrade, update, --update      Check for available updates"
  echo ""
  echo "Tmux flags:"
  echo "  --branch <branch>             Branch name for tmux session worktree"
  echo "  --new-tmux                    Create a new tmux session for the branch"
  echo "  --cmd <command>               Command to run inside the new session"
  echo ""
  echo "Examples:"
  echo "  $(basename "$0")             # interactive picker (tmux session management)"
  echo "  $(basename "$0") ls          # list worktrees only"
  echo "  $(basename "$0") ch -b feat/x # create and switch to worktree"
  echo "  $(basename "$0") --branch main --new-tmux --cmd \"git status\""
  echo "  $(basename "$0") upgrade     # check for available updates"
  echo ""
  echo "Note: tmux session management is available via flags or the interactive menu."
}



# --------------------------- Main -------------------------------------------

if [ $# -eq 0 ]; then
  # Interactive mode by default - prefer Rust TUI if available
  if command -v gw-tui >/dev/null 2>&1; then
    # Use Rust TUI if available
    set_terminal_title
    gw-tui --bridge-path "$SCRIPT_DIR/gw-bridge.sh"
  elif [[ -f "$SCRIPT_DIR/gw-tui/target/release/gw-tui" ]]; then
    # Use locally built Rust TUI
    set_terminal_title
    "$SCRIPT_DIR/gw-tui/target/release/gw-tui" --bridge-path "$SCRIPT_DIR/gw-bridge.sh"
  elif [[ -f "$SCRIPT_DIR/gw-tui/target/debug/gw-tui" ]]; then
    # Use debug build of Rust TUI
    set_terminal_title
    "$SCRIPT_DIR/gw-tui/target/debug/gw-tui" --bridge-path "$SCRIPT_DIR/gw-bridge.sh"
  else
    # No Rust TUI available - provide clear guidance
    err "Interactive mode requires the Rust TUI (gw-tui)"
    echo ""
    echo "To build:"
    echo "  ./build.sh              # Build Rust TUI binary"
    echo ""
    echo "Or build manually:"
    echo "  cd gw-tui && cargo build --release"
    echo ""
    echo "For command-line operations without interactive mode:"
    echo "  $0 ls                   # List worktrees"
    echo "  $0 ch <branch>          # Switch to worktree"
    echo "  $0 help                 # Show all commands"
    exit 1
  fi
  exit 0
fi

new_tmux=false
tmux_branch=""
tmux_cmd=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --branch|-b)
      [[ $# -lt 2 ]] && { err "--branch requires a value"; exit 1; }
      tmux_branch="$2"
      shift 2
      ;;
    --cmd|-c)
      [[ $# -lt 2 ]] && { err "--cmd requires a value"; exit 1; }
      tmux_cmd="$2"
      shift 2
      ;;
    --new-tmux)
      new_tmux=true
      shift
      ;;
    --)
      shift
      break
      ;;
    *)
      break
      ;;
  esac
done

if $new_tmux; then
  if [[ -z "$tmux_branch" || -z "$tmux_cmd" ]]; then
    err "Usage: $(basename "$0") --branch <branch> --new-tmux --cmd \"<command>\""
    exit 1
  fi
  cmd_new_tmux_session_with_command "$tmux_branch" "$tmux_cmd"
  exit $?
fi

if [[ -n "$tmux_branch" || -n "$tmux_cmd" ]]; then
  err "--branch/--cmd require --new-tmux"
  exit 1
fi

COMMAND="$1"; shift || true
case "$COMMAND" in
  b|create|add)        cmd_create_worktree "$@" ;;
  d|delete|remove|rm)  cmd_delete_worktree "$@" ;;
  ls|list)             cmd_list_worktrees ;;
  ch|checkout)         cmd_checkout_worktree "$@" ;;
  status)              cmd_status "$@" ;;
  copy-env)            cmd_copy_env "$@" ;;
  upgrade|update|--update)     "$SCRIPT_DIR/shell/gwr/check-updates.sh" ;;
  help|-h|--help)      usage ;;
  *)                   err "Unknown command '$COMMAND'"; usage ;;
 esac

exit 0
