#!/usr/bin/env bash
# ============================================================================
# Makima Cloudflare Agent — Interactive Setup Script
#
# Sets up the Cloudflare Workers project for deploying a Makima edge relay
# agent. This agent acts as a WebSocket bridge between the Makima server
# and native daemon instances running on your infrastructure.
#
# Usage:
#   chmod +x setup.sh && ./setup.sh
# ============================================================================

set -euo pipefail

# Colors
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
CYAN='\033[0;36m'
BOLD='\033[1m'
NC='\033[0m' # No Color

# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------

info()    { echo -e "${BLUE}ℹ${NC}  $*"; }
success() { echo -e "${GREEN}✔${NC}  $*"; }
warn()    { echo -e "${YELLOW}⚠${NC}  $*"; }
error()   { echo -e "${RED}✖${NC}  $*"; }

prompt() {
  local var_name="$1"
  local prompt_text="$2"
  local default_value="${3:-}"
  local value

  if [ -n "$default_value" ]; then
    echo -ne "${CYAN}?${NC} ${prompt_text} ${BOLD}[${default_value}]${NC}: "
  else
    echo -ne "${CYAN}?${NC} ${prompt_text}: "
  fi

  read -r value
  value="${value:-$default_value}"
  eval "$var_name=\"$value\""
}

confirm() {
  local prompt_text="$1"
  local default="${2:-y}"
  local yn

  if [ "$default" = "y" ]; then
    echo -ne "${CYAN}?${NC} ${prompt_text} ${BOLD}[Y/n]${NC}: "
  else
    echo -ne "${CYAN}?${NC} ${prompt_text} ${BOLD}[y/N]${NC}: "
  fi

  read -r yn
  yn="${yn:-$default}"

  case "$yn" in
    [Yy]*) return 0 ;;
    *)     return 1 ;;
  esac
}

separator() {
  echo ""
  echo -e "${BLUE}──────────────────────────────────────────────────────${NC}"
  echo ""
}

# ---------------------------------------------------------------------------
# Header
# ---------------------------------------------------------------------------

clear 2>/dev/null || true
echo ""
echo -e "${BOLD}${CYAN}"
echo "  ╔══════════════════════════════════════════════════╗"
echo "  ║          Makima Cloudflare Agent Setup           ║"
echo "  ║                                                  ║"
echo "  ║  Edge relay for distributed task orchestration   ║"
echo "  ╚══════════════════════════════════════════════════╝"
echo -e "${NC}"
echo ""

# ---------------------------------------------------------------------------
# 1. Check Prerequisites
# ---------------------------------------------------------------------------

info "Checking prerequisites..."
echo ""

missing=0

# Node.js
if command -v node &>/dev/null; then
  node_version=$(node --version)
  # Check if version is 18+
  major_version=$(echo "$node_version" | sed 's/v//' | cut -d. -f1)
  if [ "$major_version" -ge 18 ]; then
    success "Node.js ${node_version}"
  else
    error "Node.js ${node_version} (requires v18+)"
    missing=1
  fi
else
  error "Node.js not found (requires v18+)"
  missing=1
fi

# npm
if command -v npm &>/dev/null; then
  success "npm $(npm --version)"
else
  error "npm not found"
  missing=1
fi

# npx
if command -v npx &>/dev/null; then
  success "npx available"
else
  error "npx not found"
  missing=1
fi

if [ "$missing" -eq 1 ]; then
  echo ""
  error "Missing prerequisites. Please install the missing tools and try again."
  echo ""
  info "Install Node.js 18+: https://nodejs.org/"
  exit 1
fi

separator

# ---------------------------------------------------------------------------
# 2. Gather Configuration
# ---------------------------------------------------------------------------

info "Let's configure your Makima edge agent."
echo ""

prompt MAKIMA_SERVER_URL "Makima server WebSocket URL" "wss://api.makima.jp"
echo ""

prompt MAKIMA_API_KEY "Makima API key (from your server dashboard)" ""
if [ -z "$MAKIMA_API_KEY" ]; then
  error "API key is required."
  exit 1
fi
echo ""

prompt MAKIMA_AGENT_NAME "Agent display name (optional)" "makima-edge"
echo ""

separator

# ---------------------------------------------------------------------------
# 3. Install Dependencies
# ---------------------------------------------------------------------------

info "Installing dependencies..."
echo ""

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

npm install 2>&1 | while IFS= read -r line; do
  echo "  $line"
done

echo ""
success "Dependencies installed."

separator

# ---------------------------------------------------------------------------
# 4. Create .dev.vars (local secrets for development)
# ---------------------------------------------------------------------------

info "Creating .dev.vars for local development secrets..."

cat > .dev.vars <<EOF
# Makima Cloudflare Agent — Local Development Secrets
# These are used by 'wrangler dev' and should NOT be committed to git.

MAKIMA_SERVER_URL=${MAKIMA_SERVER_URL}
MAKIMA_API_KEY=${MAKIMA_API_KEY}
MAKIMA_AGENT_NAME=${MAKIMA_AGENT_NAME}
EOF

success "Created .dev.vars"
echo ""

# Ensure .dev.vars is gitignored
if [ -f .gitignore ]; then
  if ! grep -q ".dev.vars" .gitignore 2>/dev/null; then
    echo ".dev.vars" >> .gitignore
    success "Added .dev.vars to .gitignore"
  fi
else
  echo ".dev.vars" > .gitignore
  echo "node_modules/" >> .gitignore
  echo ".wrangler/" >> .gitignore
  success "Created .gitignore"
fi

separator

# ---------------------------------------------------------------------------
# 5. Wrangler Login Check
# ---------------------------------------------------------------------------

info "Checking Cloudflare authentication..."
echo ""

if npx wrangler whoami 2>/dev/null | grep -q "You are logged in"; then
  success "Already logged in to Cloudflare."
else
  warn "Not logged in to Cloudflare."
  if confirm "Would you like to log in now?"; then
    npx wrangler login
    success "Logged in to Cloudflare."
  else
    warn "Skipping login. You'll need to run 'npx wrangler login' before deploying."
  fi
fi

separator

# ---------------------------------------------------------------------------
# 6. Set Production Secrets
# ---------------------------------------------------------------------------

if confirm "Would you like to set production secrets now? (Required before first deploy)"; then
  echo ""
  info "Setting secrets via Wrangler..."
  echo ""

  echo "$MAKIMA_SERVER_URL" | npx wrangler secret put MAKIMA_SERVER_URL 2>&1 | while IFS= read -r line; do
    echo "  $line"
  done
  success "Set MAKIMA_SERVER_URL"

  echo "$MAKIMA_API_KEY" | npx wrangler secret put MAKIMA_API_KEY 2>&1 | while IFS= read -r line; do
    echo "  $line"
  done
  success "Set MAKIMA_API_KEY"

  if [ -n "$MAKIMA_AGENT_NAME" ]; then
    echo "$MAKIMA_AGENT_NAME" | npx wrangler secret put MAKIMA_AGENT_NAME 2>&1 | while IFS= read -r line; do
      echo "  $line"
    done
    success "Set MAKIMA_AGENT_NAME"
  fi
fi

separator

# ---------------------------------------------------------------------------
# 7. Deploy or Dev
# ---------------------------------------------------------------------------

echo -e "${BOLD}Setup complete!${NC} What would you like to do next?"
echo ""
echo "  1) Deploy to Cloudflare Workers (production)"
echo "  2) Start local development server"
echo "  3) Exit (deploy later)"
echo ""

prompt NEXT_ACTION "Choose an option" "3"

case "$NEXT_ACTION" in
  1)
    echo ""
    info "Deploying to Cloudflare Workers..."
    echo ""
    npx wrangler deploy 2>&1 | while IFS= read -r line; do
      echo "  $line"
    done
    echo ""
    success "Deployed! Your Makima edge agent is live."
    ;;
  2)
    echo ""
    info "Starting local development server..."
    echo ""
    info "Press Ctrl+C to stop."
    echo ""
    npx wrangler dev
    ;;
  3|*)
    ;;
esac

# ---------------------------------------------------------------------------
# 8. Next Steps
# ---------------------------------------------------------------------------

separator

echo -e "${BOLD}${GREEN}🎉 Makima Cloudflare Agent is ready!${NC}"
echo ""
echo -e "  ${BOLD}Useful commands:${NC}"
echo ""
echo -e "    ${CYAN}npm run dev${NC}      Start local development server"
echo -e "    ${CYAN}npm run deploy${NC}   Deploy to Cloudflare Workers"
echo -e "    ${CYAN}npm run tail${NC}     Stream production logs"
echo ""
echo -e "  ${BOLD}API Endpoints (after deploy):${NC}"
echo ""
echo -e "    ${CYAN}GET  /status${NC}     Agent connection status"
echo -e "    ${CYAN}GET  /health${NC}     Health check"
echo -e "    ${CYAN}GET  /tasks${NC}      Task dispatch history"
echo -e "    ${CYAN}GET  /logs${NC}       Connection event logs"
echo -e "    ${CYAN}POST /reconnect${NC}  Force upstream reconnection"
echo -e "    ${CYAN}WS   /ws/daemon${NC}  Downstream daemon WebSocket"
echo ""
echo -e "  ${BOLD}Architecture:${NC}"
echo ""
echo -e "    Makima Server  ←WebSocket→  ${CYAN}Edge Agent${NC}  ←WebSocket→  Native Daemons"
echo ""
echo -e "  ${BOLD}Documentation:${NC}"
echo -e "    See ${CYAN}README.md${NC} for full setup and architecture details."
echo ""
