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

# ─────────────────────────────────────────────────────────
# OpenCode Discord Manager — Setup wizard
# ─────────────────────────────────────────────────────────
CONFIG_DIR="${XDG_CONFIG_HOME:-$HOME/.config}/opencode"
CONFIG_FILE="$CONFIG_DIR/discord-manager.json"

echo "==> OpenCode Discord Manager Setup"

# Already configured?
if [ -f "$CONFIG_FILE" ] && jq -e '.botToken' "$CONFIG_FILE" >/dev/null 2>&1; then
  echo "    Bot token already configured in $CONFIG_FILE"
  echo "    To re-configure, delete or edit that file."
  echo ""
  echo "    Plugin installed at: $CONFIG_DIR/plugins/discord-manager.ts"
  echo "    Restart opencode and DM your bot to test."
  exit 0
fi

# Token
if [ -n "${DISCORD_BOT_TOKEN:-}" ]; then
  TOKEN="$DISCORD_BOT_TOKEN"
  echo "    Using DISCORD_BOT_TOKEN from environment"
elif [ -f "$CONFIG_FILE" ]; then
  TOKEN=$(jq -r '.botToken // empty' "$CONFIG_FILE" 2>/dev/null || echo "")
fi

if [ -z "${TOKEN:-}" ]; then
  echo ""
  echo "    Enter your Discord bot token (from https://discord.com/developers/applications)"
  echo -n "    Token: "
  read -r TOKEN
  TOKEN=$(echo "$TOKEN" | xargs)
fi

if [ -z "$TOKEN" ]; then
  echo "    No token provided. Set DISCORD_BOT_TOKEN or re-run."
  exit 1
fi

mkdir -p "$CONFIG_DIR"
echo "{\"botToken\":\"$TOKEN\"}" > "$CONFIG_FILE"
echo "    Saved token to $CONFIG_FILE"

echo ""
echo "==> Setup complete!"
echo "    Plugin located at: $CONFIG_DIR/plugins/discord-manager.ts"
echo "    Restart opencode and DM the bot to test."
echo ""
echo "    Tip: You can also set DISCORD_BOT_TOKEN in your environment."
