#!/usr/bin/env bash
set -euo pipefail

MODE="install"

for arg in "$@"; do
  case "$arg" in
    --upgrade)
      MODE="upgrade"
      ;;
    *)
      echo "Unknown option: $arg" >&2
      echo "Usage: ./scripts/install-twitter-cli.sh [--upgrade]" >&2
      exit 1
      ;;
  esac
done

choose_installer() {
  if command -v uv >/dev/null 2>&1; then
    echo "uv"
    return
  fi
  if command -v pipx >/dev/null 2>&1; then
    echo "pipx"
    return
  fi
  echo ""
}

print_existing_version() {
  if command -v twitter >/dev/null 2>&1; then
    echo "twitter-cli is already available: $(twitter --version 2>/dev/null || echo 'version unknown')"
  fi
}

INSTALLER="$(choose_installer)"

if [ -z "$INSTALLER" ]; then
  echo "ERROR: Neither 'uv' nor 'pipx' is installed." >&2
  echo "Install one of them first, then re-run this script." >&2
  echo "Examples:" >&2
  echo "  curl -LsSf https://astral.sh/uv/install.sh | sh" >&2
  echo "  python3 -m pip install --user pipx && python3 -m pipx ensurepath" >&2
  exit 1
fi

print_existing_version

case "$INSTALLER" in
  uv)
    if [ "$MODE" = "upgrade" ]; then
      echo "Upgrading twitter-cli with uv..."
      uv tool upgrade twitter-cli
    else
      echo "Installing twitter-cli with uv (with xclienttransaction)..."
      uv tool install --reinstall twitter-cli --with xclienttransaction
    fi
    ;;
  pipx)
    if [ "$MODE" = "upgrade" ]; then
      echo "Upgrading twitter-cli with pipx..."
      pipx upgrade twitter-cli
      echo "Injecting xclienttransaction..."
      pipx inject twitter-cli xclienttransaction || true
    else
      echo "Installing twitter-cli with pipx..."
      pipx install --force twitter-cli
      echo "Injecting xclienttransaction..."
      pipx inject twitter-cli xclienttransaction || true
    fi
    ;;
esac

if ! command -v twitter >/dev/null 2>&1; then
  echo "WARN: Installation finished but 'twitter' is not on PATH." >&2
  echo "Set tools.x_cli_command in config.yaml to the installed binary path." >&2
  exit 0
fi

echo ""
echo "twitter-cli ready: $(twitter --version 2>/dev/null || echo 'version unknown')"

# 動作確認: search --help が正常に実行できるかテスト
echo ""
echo "Running smoke test (twitter search --help)..."
if twitter search --help >/dev/null 2>&1; then
  echo "Smoke test passed."
else
  echo "WARN: 'twitter search --help' failed. twitter-cli may not work correctly." >&2
  echo "Try reinstalling: ./scripts/install-twitter-cli.sh" >&2
fi

echo ""
echo "Next:"
echo "  1. Put cookies into config.yaml if needed (tools.x_auth_token / tools.x_ct0)"
echo "  2. Use XSearch / XUserPosts / XPostDetail from general or research"
