#!/usr/bin/env bash
# x-adapter インストーラ。
#
# 何をするか:
#   X.com の x-web バンドル移行で twitter-cli の transaction-id 生成が壊れたため、
#   twscrape (新バンドル対応の XClIdGen) + twikit を使う twitter-cli 互換アダプタを
#   隔離 venv に入れ、`x-adapter` という実行ファイルを ~/.local/bin に置く。
#
# 使い方:
#   ./scripts/install-x-adapter.sh            # 新規インストール
#   ./scripts/install-x-adapter.sh --upgrade  # twscrape/twikit を最新へ (X が再破壊した時の修復レバー)
#
# 終わったら config.yaml に:
#   tools:
#     x_cli_command: [x-adapter]
set -euo pipefail

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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
SRC="$SCRIPT_DIR/x-adapter/x_adapter.py"
REQ="$SCRIPT_DIR/x-adapter/requirements.txt"

PREFIX="${X_ADAPTER_PREFIX:-$HOME/.local/share/x-adapter}"
BIN_DIR="${X_ADAPTER_BIN:-$HOME/.local/bin}"
VENV="$PREFIX/venv"

if [ ! -f "$SRC" ]; then
  echo "ERROR: $SRC not found." >&2
  exit 1
fi

mkdir -p "$PREFIX" "$BIN_DIR"

if [ ! -d "$VENV" ]; then
  echo "Creating venv at $VENV ..."
  python3 -m venv "$VENV"
fi

echo "Installing/upgrading dependencies ..."
"$VENV/bin/pip" install -q --upgrade pip >/dev/null
if [ "$MODE" = "upgrade" ]; then
  "$VENV/bin/pip" install -q --upgrade twscrape twikit httpx PyYAML
else
  "$VENV/bin/pip" install -q -r "$REQ"
fi

echo "Installing x_adapter.py ..."
cp "$SRC" "$PREFIX/x_adapter.py"

WRAPPER="$BIN_DIR/x-adapter"
cat > "$WRAPPER" <<EOF
#!/usr/bin/env bash
exec "$VENV/bin/python" "$PREFIX/x_adapter.py" "\$@"
EOF
chmod +x "$WRAPPER"

echo ""
echo "x-adapter ready: $("$WRAPPER" --version 2>/dev/null || echo 'version unknown')"

echo ""
echo "Smoke test (x-adapter --version) ..."
if "$WRAPPER" --version >/dev/null 2>&1; then
  echo "Smoke test passed."
else
  echo "WARN: x-adapter --version failed." >&2
fi

echo ""
echo "Next:"
echo "  1. Ensure cookies are set in config.yaml (tools.x_auth_token / tools.x_ct0)"
echo "  2. Set tools.x_cli_command: [x-adapter]   (or [$WRAPPER] if ~/.local/bin is not on PATH)"
echo "  3. Restart the server. XSearch / XUserPosts / XPostDetail / XTimeline now route through x-adapter."
echo ""
echo "If X breaks scraping again (every 2-4 weeks): ./scripts/install-x-adapter.sh --upgrade"
