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

# ── Fred Installer ──────────────────────────────────────────────────
# Usage:
#   curl -sSL https://releases.askfred.xyz/install.sh | sudo bash
#
# Or with a custom release server:
#   curl -sSL ... | sudo FRED_URL=https://your-server.com/releases bash
#
# Or install a specific version:
#   curl -sSL ... | sudo bash -s v0.2.0
# ────────────────────────────────────────────────────────────────────

INSTALL_DIR="/opt/fred"
FRED_USER="fred"

# ── Release server URL (override with FRED_URL env var) ──
BASE_URL="${FRED_URL:-https://releases.askfred.xyz/releases}"

# ── Colors ──
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BOLD='\033[1m'
NC='\033[0m'

info()  { echo -e "${GREEN}[+]${NC} $*"; }
warn()  { echo -e "${YELLOW}[!]${NC} $*"; }
error() { echo -e "${RED}[✗]${NC} $*"; exit 1; }

validate_base_url_security() {
  if [[ "$BASE_URL" == http://* ]]; then
    warn "Using insecure HTTP downloads. Set FRED_URL to an HTTPS URL for production."
  fi
}

curl_fetch_text() {
  local url="$1"
  if [[ "$url" == https://* ]]; then
    curl --silent --show-error --location --fail --proto '=https' --tlsv1.2 "$url"
  else
    curl --silent --show-error --location --fail "$url"
  fi
}

curl_fetch_file() {
  local url="$1"
  local output="$2"
  if [[ "$url" == https://* ]]; then
    curl --silent --show-error --location --fail --proto '=https' --tlsv1.2 -o "$output" "$url"
  else
    curl --silent --show-error --location --fail -o "$output" "$url"
  fi
}

sha256_of() {
  local file="$1"
  if command -v sha256sum >/dev/null 2>&1; then
    sha256sum "$file" | awk '{print $1}'
  elif command -v shasum >/dev/null 2>&1; then
    shasum -a 256 "$file" | awk '{print $1}'
  else
    error "Missing sha256 tool (install sha256sum or shasum)"
  fi
}

verify_sha256_file() {
  local archive="$1"
  local checksum_file="$2"
  local expected
  expected="$(awk '{print $1}' "$checksum_file" | tr -d '[:space:]')"
  [[ "$expected" =~ ^[A-Fa-f0-9]{64}$ ]] || error "Invalid checksum file: ${checksum_file}"

  local actual
  actual="$(sha256_of "$archive")"
  [[ "$actual" == "$expected" ]] || error "Checksum verification failed for $(basename "$archive")"
}

# ── Preflight ──

[[ $EUID -eq 0 ]] || error "Please run as root (sudo bash install.sh)"

command -v curl >/dev/null 2>&1 || error "curl is required but not installed"
command -v tar >/dev/null 2>&1 || error "tar is required but not installed"
validate_base_url_security

# ── Detect platform ──

OS="$(uname -s | tr '[:upper:]' '[:lower:]')"
ARCH="$(uname -m)"

case "$OS" in
  linux)  OS="linux" ;;
  darwin) error "macOS is not supported by this installer. Use a Linux VPS (systemd)." ;;
  *)      error "Unsupported OS: $OS" ;;
esac

case "$ARCH" in
  x86_64|amd64)   ARCH="amd64" ;;
  aarch64|arm64)   ARCH="arm64" ;;
  *)               error "Unsupported architecture: $ARCH" ;;
esac

ARCHIVE="fred-${OS}-${ARCH}.tar.gz"
info "Detected platform: ${OS}/${ARCH}"

# ── Resolve version ──

VERSION="${1:-latest}"
if [[ "$VERSION" == "latest" ]]; then
  info "Fetching latest version..."
  VERSION=$(curl_fetch_text "${BASE_URL}/LATEST") \
    || error "Could not fetch latest version from ${BASE_URL}/LATEST"
  VERSION=$(echo "$VERSION" | tr -d '[:space:]')
  [[ -n "$VERSION" ]] || error "Empty version returned from ${BASE_URL}/LATEST"
fi
info "Installing Fred ${VERSION}"

# ── Download ──

DOWNLOAD_URL="${BASE_URL}/${VERSION}/${ARCHIVE}"
CHECKSUM_URL="${DOWNLOAD_URL}.sha256"
TMPDIR=$(mktemp -d)
trap 'rm -rf "$TMPDIR"' EXIT

info "Downloading ${DOWNLOAD_URL}..."
curl_fetch_file "$DOWNLOAD_URL" "${TMPDIR}/${ARCHIVE}" \
  || error "Download failed: ${DOWNLOAD_URL}"
curl_fetch_file "$CHECKSUM_URL" "${TMPDIR}/${ARCHIVE}.sha256" \
  || error "Checksum download failed: ${CHECKSUM_URL}"
verify_sha256_file "${TMPDIR}/${ARCHIVE}" "${TMPDIR}/${ARCHIVE}.sha256"

# ── Create system user ──

if ! id "$FRED_USER" &>/dev/null; then
  info "Creating system user: ${FRED_USER}"
  useradd --system --shell /usr/sbin/nologin --home-dir "$INSTALL_DIR" "$FRED_USER"
fi

# ── Install files ──

info "Installing to ${INSTALL_DIR}..."
mkdir -p "${INSTALL_DIR}"/{data,logs,workspace,skills}

tar -xzf "${TMPDIR}/${ARCHIVE}" -C "$INSTALL_DIR"
for required in fred config.toml fred.service upgrade.sh uninstall.sh healthcheck.sh; do
  [[ -f "${INSTALL_DIR}/${required}" ]] || error "Release archive is missing ${required}"
done
chmod +x \
  "${INSTALL_DIR}/fred" \
  "${INSTALL_DIR}/upgrade.sh" \
  "${INSTALL_DIR}/uninstall.sh" \
  "${INSTALL_DIR}/healthcheck.sh"

# ── Environment file (interactive) ──

if [[ ! -f "${INSTALL_DIR}/.env" ]]; then
  info "Setting up API keys..."
  echo ""

  read -rp "$(echo -e "${BOLD}Telegram Bot Token${NC} (from @BotFather): ")" TELEGRAM_TOKEN
  [[ -n "$TELEGRAM_TOKEN" ]] || error "Telegram bot token is required"

  echo ""
  echo -e "${BOLD}Choose your LLM provider:${NC}"
  echo "  1) Anthropic (Claude) — recommended"
  echo "  2) OpenRouter (access to multiple models)"
  echo "  3) OpenAI"
  echo "  4) Google Gemini"
  read -rp "Provider [1]: " PROVIDER_CHOICE
  PROVIDER_CHOICE="${PROVIDER_CHOICE:-1}"

  case "$PROVIDER_CHOICE" in
    1)
      read -rp "$(echo -e "${BOLD}Anthropic API Key${NC}: ")" LLM_KEY
      LLM_ENV="ANTHROPIC_API_KEY"
      LLM_PROVIDER="anthropic"
      LLM_MODEL="claude-sonnet-4-20250514"
      ;;
    2)
      read -rp "$(echo -e "${BOLD}OpenRouter API Key${NC}: ")" LLM_KEY
      LLM_ENV="OPENROUTER_API_KEY"
      LLM_PROVIDER="openrouter"
      LLM_MODEL="anthropic/claude-sonnet-4-20250514"
      ;;
    3)
      read -rp "$(echo -e "${BOLD}OpenAI API Key${NC}: ")" LLM_KEY
      LLM_ENV="OPENAI_API_KEY"
      LLM_PROVIDER="openai"
      LLM_MODEL="gpt-4o"
      ;;
    4)
      read -rp "$(echo -e "${BOLD}Gemini API Key${NC}: ")" LLM_KEY
      LLM_ENV="GEMINI_API_KEY"
      LLM_PROVIDER="gemini"
      LLM_MODEL="gemini-2.5-flash"
      ;;
    *)
      error "Invalid choice"
      ;;
  esac

  [[ -n "$LLM_KEY" ]] || error "API key is required"

  cat > "${INSTALL_DIR}/.env" <<ENVEOF
TELEGRAM_BOT_TOKEN=${TELEGRAM_TOKEN}
${LLM_ENV}=${LLM_KEY}
ENVEOF

  chmod 600 "${INSTALL_DIR}/.env"
  info "Wrote ${INSTALL_DIR}/.env"

  # Update [model] in config.toml to match the selected provider.
  # Keep [model.fallback] and [[providers]] entries unchanged.
  if [[ "$PROVIDER_CHOICE" != "1" ]]; then
    info "Updating config.toml for ${LLM_PROVIDER}..."
    sed -i.bak \
      -e "/^\\[model\\]$/,/^\\[/{s/^provider = .*/provider = \"${LLM_PROVIDER}\"/; s/^model = .*/model = \"${LLM_MODEL}\"/; s/^api_key_env = .*/api_key_env = \"${LLM_ENV}\"/;}" \
      "${INSTALL_DIR}/config.toml"
    rm -f "${INSTALL_DIR}/config.toml.bak"
  fi
else
  warn "Existing .env found, skipping API key setup"
fi

# ── Fix ownership ──

chown -R "${FRED_USER}:${FRED_USER}" "$INSTALL_DIR"

# ── Install systemd service ──

if command -v systemctl &>/dev/null; then
  info "Installing systemd service..."
  cp "${INSTALL_DIR}/fred.service" /etc/systemd/system/fred.service
  systemctl daemon-reload
  systemctl enable fred

  echo ""
  read -rp "$(echo -e "${BOLD}Start Fred now?${NC} [Y/n]: ")" START_NOW
  START_NOW="${START_NOW:-Y}"

  if [[ "$START_NOW" =~ ^[Yy] ]]; then
    systemctl start fred
    sleep 2
    if systemctl is-active --quiet fred; then
      info "Fred is running!"
    else
      warn "Service started but may have issues. Check: journalctl -u fred -f"
    fi
  fi
else
  warn "systemd not found — you'll need to run ${INSTALL_DIR}/fred manually"
fi

# ── Done ──

echo ""
echo -e "${GREEN}════════════════════════════════════════${NC}"
echo -e "${GREEN}  Fred installed successfully!${NC}"
echo -e "${GREEN}════════════════════════════════════════${NC}"
echo ""
echo -e "  ${BOLD}Next steps:${NC}"
echo -e "  1. Open Telegram and message your bot"
echo -e "  2. Enter the pairing code shown in the logs"
echo -e "     ${YELLOW}journalctl -u fred -f${NC}"
echo ""
echo -e "  ${BOLD}Useful commands:${NC}"
echo -e "  Status:   ${YELLOW}systemctl status fred${NC}"
echo -e "  Logs:     ${YELLOW}journalctl -u fred -f${NC}"
echo -e "  Restart:  ${YELLOW}sudo systemctl restart fred${NC}"
echo -e "  Config:   ${YELLOW}sudo nano ${INSTALL_DIR}/config.toml${NC}"
echo ""
