#!/bin/bash
set -e

# Wrap everything in a function so `curl | bash` reads the entire
# script into memory before executing.  Without this, bash reads
# line-by-line from the pipe and `read` consumes script lines as input.
main() {

# Ensure ~/.local/bin is in PATH (where ghost-tab-tui gets installed)
export PATH="$HOME/.local/bin:$PATH"

# Determine where supporting files live
SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
SHARE_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"

source "$SHARE_DIR/lib/tui.sh"
source "$SHARE_DIR/lib/install.sh"
source "$SHARE_DIR/lib/terminal-select-tui.sh"
source "$SHARE_DIR/lib/terminals/registry.sh"
source "$SHARE_DIR/lib/terminals/adapter.sh"
source "$SHARE_DIR/lib/settings-json.sh"
source "$SHARE_DIR/lib/ai-select-tui.sh"
source "$SHARE_DIR/lib/statusline-setup.sh"
source "$SHARE_DIR/lib/project-actions.sh"
source "$SHARE_DIR/lib/project-actions-tui.sh"
source "$SHARE_DIR/lib/update.sh"

# ---------- Terminal-only setup ----------
run_terminal_setup() {
  local share_dir="$1"

  # Ensure TUI binary is up to date (--terminal path skips main flow checks)
  header "Checking TUI binary..."
  if ! ensure_ghost_tab_tui "$share_dir"; then
    exit 1
  fi

  header "Selecting terminal..."
  echo ""
  echo -e "  Ghost Tab supports multiple terminal emulators."
  echo -e "  Select your preferred terminal:"
  echo ""

  if select_terminal_interactive; then
    if [[ -z "$_selected_terminal" ]]; then
      error "Internal error: TUI did not set terminal"
      exit 1
    fi
    local selected_terminal="$_selected_terminal"

    # Save preference
    local pref_dir="${XDG_CONFIG_HOME:-$HOME/.config}/ghost-tab"
    mkdir -p "$pref_dir"
    save_terminal_preference "$selected_terminal" "$pref_dir/terminal"

    echo ""
    success "Selected terminal: $(get_terminal_display_name "$selected_terminal")"

    # Install terminal if needed
    header "Checking $(get_terminal_display_name "$selected_terminal")..."
    load_terminal_adapter "$selected_terminal"
    if ! terminal_install; then
      error "Terminal installation failed. Install manually and re-run: ghost-tab --terminal"
      exit 1
    fi

    # Ensure wrapper symlink exists
    header "Setting up wrapper script..."
    local wrapper_dir="${XDG_CONFIG_HOME:-$HOME/.config}/ghost-tab"
    mkdir -p "$wrapper_dir"
    ln -sf "$share_dir/wrapper.sh" "$wrapper_dir/wrapper.sh"
    success "Linked wrapper.sh in $wrapper_dir/"

    if [ -d "$share_dir/lib" ]; then
      [ -d "$wrapper_dir/lib" ] && [ ! -L "$wrapper_dir/lib" ] && rm -rf "${wrapper_dir:?}/lib"
      ln -sfn "$share_dir/lib" "$wrapper_dir/lib"
    fi

    # Configure terminal
    header "Setting up $(get_terminal_display_name "$selected_terminal") config..."
    local terminal_config
    terminal_config="$(terminal_get_config_path)"
    local wrapper_path
    wrapper_path="$(terminal_get_wrapper_path)"

    if [ -f "$terminal_config" ]; then
      warn "Existing config found at $terminal_config"
      echo ""
      echo -e "  ${_BOLD}1)${_NC} Merge — add the wrapper command to your existing config"
      echo -e "  ${_BOLD}2)${_NC} Skip — don't modify the config (manual setup required)"
      echo ""
      read -rn1 -p "$(echo -e "${_BLUE}Choose (1/2):${_NC} ")" config_choice </dev/tty
      echo ""

      case "$config_choice" in
        1) terminal_setup_config "$terminal_config" "$wrapper_path" ;;
        *) info "Skipped config modification. Add the wrapper manually." ;;
      esac
    else
      mkdir -p "$(dirname "$terminal_config")"
      terminal_setup_config "$terminal_config" "$wrapper_path"
    fi

    echo ""
    success "Terminal configured: $(get_terminal_display_name "$selected_terminal")"
    info "Open a new $(get_terminal_display_name "$selected_terminal") window to start coding."
  else
    warn "Terminal setup did not complete. Run 'ghost-tab --terminal' to try again."
    exit 1
  fi
}

# ---------- Argument parsing ----------
case "${1:-}" in
  --terminal)
    run_terminal_setup "$SHARE_DIR"
    exit 0
    ;;
  --*)
    error "Unknown flag: $1"
    echo "Usage: ghost-tab [--terminal]"
    exit 1
    ;;
esac

# ---------- OS check ----------
header "Checking platform..."
if [ "$(uname)" != "Darwin" ]; then
  error "This setup script only supports macOS."
  exit 1
fi
success "macOS detected"
notify_if_update_available

# ---------- Dependencies ----------
header "Installing dependencies..."
ensure_base_requirements

# ---------- TUI Binary ----------
header "Checking TUI binary..."
if ! ensure_ghost_tab_tui "$SHARE_DIR"; then
  exit 1
fi

# ---------- AI Coding Tools ----------
header "Setting up AI coding tools..."
echo ""
echo -e "  Ghost Tab supports multiple AI coding assistants."
echo -e "  Select your preferred AI tool:"
echo ""

# Use TUI to select AI tool
if select_ai_tool_interactive; then
  # Variable set by select_ai_tool_interactive: _selected_ai_tool
  if [[ -z "$_selected_ai_tool" ]]; then
    error "Internal error: TUI did not set AI tool"
    exit 1
  fi
  SELECTED_AI_TOOL="$_selected_ai_tool"

  # Save preference
  AI_TOOL_PREF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/ghost-tab"
  mkdir -p "$AI_TOOL_PREF_DIR"
  echo "$SELECTED_AI_TOOL" > "$AI_TOOL_PREF_DIR/ai-tool"

  echo ""
  success "Selected AI tool: $SELECTED_AI_TOOL"

  # Install the selected tool
  case "$SELECTED_AI_TOOL" in
    claude)
      ensure_command "claude" "curl -fsSL https://claude.ai/install.sh | bash" \
        "Run 'claude' to authenticate before launching Ghost Tab." "Claude Code"
      ;;
    codex)
      ensure_command "codex" "brew install --cask codex" "" "Codex CLI"
      ;;
    copilot)
      ensure_command "copilot" "brew install copilot-cli" "" "Copilot CLI"
      ;;
    opencode)
      ensure_opencode
      ;;
  esac
else
  info "AI tool selection cancelled"
  exit 1
fi

# ---------- Terminal Selection ----------
header "Selecting terminal..."
echo ""
echo -e "  Ghost Tab supports multiple terminal emulators."
echo -e "  Select your preferred terminal:"
echo ""

if select_terminal_interactive; then
  if [[ -z "$_selected_terminal" ]]; then
    error "Internal error: TUI did not set terminal"
    exit 1
  fi
  SELECTED_TERMINAL="$_selected_terminal"

  # Save preference
  TERMINAL_PREF_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/ghost-tab"
  mkdir -p "$TERMINAL_PREF_DIR"
  save_terminal_preference "$SELECTED_TERMINAL" "$TERMINAL_PREF_DIR/terminal"

  echo ""
  success "Selected terminal: $(get_terminal_display_name "$SELECTED_TERMINAL")"
else
  warn "Terminal setup did not complete. Run 'ghost-tab --terminal' to try again."
  exit 1
fi

# ---------- Terminal Installation ----------
header "Checking $(get_terminal_display_name "$SELECTED_TERMINAL")..."
load_terminal_adapter "$SELECTED_TERMINAL"
if ! terminal_install; then
  error "Terminal installation failed. Install manually and re-run: ghost-tab --terminal"
  exit 1
fi

# Verify supporting files exist
if [ ! -f "$SHARE_DIR/wrapper.sh" ] || [ ! -d "$SHARE_DIR/templates" ]; then
  error "Supporting files not found in $SHARE_DIR. Re-clone the repo and try again."
  exit 1
fi

# ---------- Wrapper Script ----------
header "Setting up wrapper script..."
WRAPPER_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/ghost-tab"
mkdir -p "$WRAPPER_DIR"
ln -sf "$SHARE_DIR/wrapper.sh" "$WRAPPER_DIR/wrapper.sh"
success "Linked wrapper.sh in $WRAPPER_DIR/"

# Symlink shared libraries (remove old copies if present)
if [ -d "$SHARE_DIR/lib" ]; then
  [ -d "$WRAPPER_DIR/lib" ] && [ ! -L "$WRAPPER_DIR/lib" ] && rm -rf "${WRAPPER_DIR:?}/lib"
  ln -sfn "$SHARE_DIR/lib" "$WRAPPER_DIR/lib"
  success "Linked shared libraries to $WRAPPER_DIR/lib/"
fi

# ---------- Ghost Tab CLI Command ----------
header "Setting up ghost-tab command..."
ln -sf "$SHARE_DIR/bin/ghost-tab-config" "$HOME/.local/bin/ghost-tab"
success "Created ghost-tab command at ~/.local/bin/ghost-tab"

# ---------- Terminal Config ----------
header "Setting up $(get_terminal_display_name "$SELECTED_TERMINAL") config..."
TERMINAL_CONFIG="$(terminal_get_config_path)"
WRAPPER_PATH="$(terminal_get_wrapper_path)"

if [ -f "$TERMINAL_CONFIG" ]; then
  warn "Existing config found at $TERMINAL_CONFIG"
  echo ""
  echo -e "  ${_BOLD}1)${_NC} Merge — add the wrapper command to your existing config"
  echo -e "  ${_BOLD}2)${_NC} Skip — don't modify the config (manual setup required)"
  echo ""
  read -rn1 -p "$(echo -e "${_BLUE}Choose (1/2):${_NC} ")" config_choice </dev/tty
  echo ""

  case "$config_choice" in
    1) terminal_setup_config "$TERMINAL_CONFIG" "$WRAPPER_PATH" ;;
    *) info "Skipped config modification. Add the wrapper manually." ;;
  esac
else
  mkdir -p "$(dirname "$TERMINAL_CONFIG")"
  terminal_setup_config "$TERMINAL_CONFIG" "$WRAPPER_PATH"
fi

# Migrate from old config location
OLD_PROJECTS_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/vibecode-editor"
NEW_PROJECTS_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/ghost-tab"
if [ -d "$OLD_PROJECTS_DIR" ] && [ ! -d "$NEW_PROJECTS_DIR" ]; then
  mv "$OLD_PROJECTS_DIR" "$NEW_PROJECTS_DIR"
  info "Migrated config from vibecode-editor to ghost-tab"
fi

# ---------- Projects ----------
header "Setting up projects..."
PROJECTS_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/ghost-tab"
PROJECTS_FILE="$PROJECTS_DIR/projects"
mkdir -p "$PROJECTS_DIR"

echo ""
read -rn1 -p "$(echo -e "${_BLUE}Add a project? (y/n):${_NC} ")" add_project </dev/tty
echo ""

while [[ "$add_project" =~ ^[yY]$ ]]; do
  if add_project_interactive; then
    # shellcheck disable=SC2154  # _add_project_name and _add_project_path are set by add_project_interactive
    add_project_to_file "$_add_project_name" "$_add_project_path" "$PROJECTS_FILE"
    success "Added project: $_add_project_name"
  else
    info "Cancelled"
  fi

  echo ""
  read -rn1 -p "$(echo -e "${_BLUE}Add another? (y/n):${_NC} ")" add_project </dev/tty
  echo ""
done

if [ -f "$PROJECTS_FILE" ] && [ -s "$PROJECTS_FILE" ]; then
  success "Projects saved to $PROJECTS_FILE"
else
  info "No projects added. Add them later to $PROJECTS_FILE"
fi

# ---------- Claude Code Status Line ----------
if [ "$SELECTED_AI_TOOL" = "claude" ]; then
  header "Setting up Claude Code status line..."
  CLAUDE_SETTINGS="$HOME/.claude/settings.json"
  setup_statusline "$SHARE_DIR" "$CLAUDE_SETTINGS" "$HOME"
else
  header "Skipping Claude Code status line..."
  info "Status line features are only available with Claude Code"
fi

# Codex CLI status line (always configure if Codex is selected)
if [ "$SELECTED_AI_TOOL" = "codex" ]; then
  header "Setting up Codex CLI status line..."
  mkdir -p ~/.codex
  # Only add status_line if not already present
  if [ ! -f ~/.codex/config.toml ] || ! grep -q 'status_line' ~/.codex/config.toml 2>/dev/null; then
    if ! grep -q '^\[tui\]' ~/.codex/config.toml 2>/dev/null; then
      printf '\n[tui]\n' >> ~/.codex/config.toml
    fi
    printf 'status_line = ["model-with-reasoning", "git-branch", "context-remaining", "used-tokens"]\n' >> ~/.codex/config.toml
    success "Codex CLI status line configured (model, branch, context, tokens)"
  else
    success "Codex CLI status line already configured"
  fi
fi

# OpenCode plugin (install/upgrade for idle notification debounce)
if [ "$SELECTED_AI_TOOL" = "opencode" ]; then
  header "Setting up OpenCode plugin..."
  _oc_plugin_dir="${XDG_CONFIG_HOME:-$HOME/.config}/opencode/plugins"
  _oc_plugin_src="$SHARE_DIR/templates/opencode-plugin.ts"
  _oc_plugin_dst="$_oc_plugin_dir/ghost-tab.ts"
  if [ -f "$_oc_plugin_src" ]; then
    mkdir -p "$_oc_plugin_dir"
    cp "$_oc_plugin_src" "$_oc_plugin_dst"
    success "OpenCode plugin installed at $_oc_plugin_dst"
  else
    warn "OpenCode plugin template not found at $_oc_plugin_src"
  fi
fi

# ---------- Summary ----------
header "Setup complete!"
echo ""
success "Wrapper script:  ~/.config/ghost-tab/wrapper.sh (symlink)"
_terminal_pref="$(cat "${XDG_CONFIG_HOME:-$HOME/.config}/ghost-tab/terminal" 2>/dev/null)"
success "Terminal:        $(get_terminal_display_name "$_terminal_pref")"
_ai_default="$(cat "${XDG_CONFIG_HOME:-$HOME/.config}/ghost-tab/ai-tool" 2>/dev/null)"
success "AI tool:         $(echo "$_ai_default" | sed 's/claude/Claude Code/;s/codex/Codex CLI/;s/copilot/Copilot CLI/;s/opencode/OpenCode/')"
success "Projects file:   $PROJECTS_FILE"
success "Config command:  ghost-tab (in ~/.local/bin/)"
if [ -f ~/.claude/statusline-wrapper.sh ]; then
  success "Status line:     ~/.claude/statusline-wrapper.sh"
fi
if [ -f ~/.codex/config.toml ]; then
  success "Codex config:    ~/.codex/config.toml"
fi
if [ -f "${XDG_CONFIG_HOME:-$HOME/.config}/opencode/plugins/ghost-tab.ts" ]; then
  success "OpenCode plugin: ~/.config/opencode/plugins/ghost-tab.ts"
fi
echo ""
info "Run 'ghost-tab' to manage configuration, or open a new $(get_terminal_display_name "${SELECTED_TERMINAL:-$_terminal_pref}") window to start coding."

} # end main

main "$@"
