#!/usr/bin/env bash
# ╔═══════════════════════════════════════════════════════╗
# ║   NexaCore AI VPS — Claude Code Template v1.0.0      ║
# ║   https://nexacore.cl                                  ║
# ╚═══════════════════════════════════════════════════════╝
# Usage:
#   bash <(curl -s https://templates.nexacore.cl/v1/claude-code/install.sh)
#   or with domain:
#   DOMAIN=code.example.com bash <(curl -s https://templates.nexacore.cl/v1/claude-code/install.sh)
set -euo pipefail

VERSION="1.0.0"
TEMPLATE_NAME="Claude Code"
SERVICE_NAME="claude-code"
DEFAULT_PORT="8080"

# ── Source common helpers ──────────────────────────────────────────────────────
SCRIPTS_URL="${NEXACORE_SCRIPTS_URL:-https://templates.nexacore.cl/scripts/common}"
_LOCAL_SCRIPTS="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)/../../.."

source_lib() {
  local lib="$1"
  local local_path="${_LOCAL_SCRIPTS}/scripts/common/${lib}"
  if [[ -f "$local_path" ]]; then
    # shellcheck source=/dev/null
    source "$local_path"
  else
    # shellcheck source=/dev/null
    source <(curl -fsSL "${SCRIPTS_URL}/${lib}" 2>/dev/null) \
      || { echo "[✘] Failed to load ${lib}"; exit 1; }
  fi
}

source_lib utils.sh
source_lib install_docker.sh
source_lib install_caddy.sh
source_lib setup_firewall.sh
source_lib setup_fail2ban.sh
source_lib setup_ssh.sh
source_lib setup_directories.sh
source_lib setup_logging.sh

# ── Config ────────────────────────────────────────────────────────────────────
DOMAIN="${DOMAIN:-}"
APP_DIR="${NEXACORE_BASE_DIR}/apps/${SERVICE_NAME}"
export NEXACORE_LOG_FILE="${NEXACORE_LOG_DIR}/install-${SERVICE_NAME}.log"

# ── Prompt for domain if not set ──────────────────────────────────────────────
prompt_domain() {
  if [[ -z "$DOMAIN" ]]; then
    echo -e "${Y}Enter the domain for this service (e.g. code.yourdomain.com):${X}"
    read -r DOMAIN
    [[ -n "$DOMAIN" ]] || die "Domain is required"
  fi
}

# ── Install Node.js LTS ───────────────────────────────────────────────────────
install_nodejs() {
  if has_cmd node; then
    info "Node.js already installed ($(node --version))"
    return 0
  fi
  step "Installing Node.js LTS..."
  curl -fsSL https://deb.nodesource.com/setup_lts.x | bash - >> "$NEXACORE_LOG_FILE" 2>&1
  apt_install nodejs
  info "Node.js installed: $(node --version)"
}

# ── Install Claude Code CLI ───────────────────────────────────────────────────
install_claude_code() {
  if has_cmd claude; then
    info "Claude Code already installed ($(claude --version 2>/dev/null | head -1))"
    return 0
  fi
  step "Installing Claude Code CLI..."
  npm install -g @anthropic-ai/claude-code >> "$NEXACORE_LOG_FILE" 2>&1 \
    || die "Failed to install Claude Code"
  info "Claude Code installed: $(claude --version 2>/dev/null | head -1)"
}

# ── Install dev tools ─────────────────────────────────────────────────────────
install_dev_tools() {
  step "Installing development tools..."
  apt_install git python3 python3-pip python3-venv build-essential curl wget unzip
  info "Dev tools installed (git, python3, build-essential)"
}

# ── Deploy code-server (VSCode in browser) ────────────────────────────────────
deploy_codeserver() {
  local password; password=$(gen_password 20)
  local hashed_password; hashed_password=$(echo -n "$password" | sha256sum | cut -d' ' -f1)

  mkdir -p "${APP_DIR}" "${NEXACORE_BASE_DIR}/data/${SERVICE_NAME}/workspace"

  cat > "${APP_DIR}/docker-compose.yml" <<EOF
version: "3.9"
services:
  code-server:
    image: codercom/code-server:latest
    container_name: nexacore-claude-code
    restart: unless-stopped
    ports:
      - "127.0.0.1:${DEFAULT_PORT}:8080"
    environment:
      - PASSWORD=${password}
    volumes:
      - ${NEXACORE_BASE_DIR}/data/${SERVICE_NAME}/workspace:/home/coder/workspace
      - ${NEXACORE_BASE_DIR}/data/${SERVICE_NAME}/.local:/home/coder/.local
    labels:
      - "com.nexacore.template=claude-code"
      - "com.nexacore.version=${VERSION}"
EOF

  step "Starting code-server container..."
  docker compose -f "${APP_DIR}/docker-compose.yml" up -d >> "$NEXACORE_LOG_FILE" 2>&1
  info "code-server started"

  # Save credentials
  cat > "${NEXACORE_BASE_DIR}/configs/${SERVICE_NAME}/credentials.txt" <<EOF
# Generated by NexaCore AI VPS Platform
# $(date)
DOMAIN=${DOMAIN}
CODE_SERVER_PASSWORD=${password}
URL=https://${DOMAIN}
EOF
  chmod 600 "${NEXACORE_BASE_DIR}/configs/${SERVICE_NAME}/credentials.txt"
  echo "$password"
}

# ── Main ──────────────────────────────────────────────────────────────────────
main() {
  require_root
  require_ubuntu
  print_banner "$TEMPLATE_NAME"
  prompt_domain

  step "[1/9] Setting up logging..."
  setup_logging

  step "[2/9] Updating system..."
  apt_update
  DEBIAN_FRONTEND=noninteractive apt-get upgrade -y -q >> "$NEXACORE_LOG_FILE" 2>&1

  step "[3/9] Creating directories..."
  setup_directories "$SERVICE_NAME"

  step "[4/9] Installing Docker..."
  install_docker

  step "[5/9] Installing development tools..."
  install_dev_tools

  step "[6/9] Installing Node.js + Claude Code CLI..."
  install_nodejs
  install_claude_code

  step "[7/9] Deploying code-server..."
  local password
  password=$(deploy_codeserver)

  step "[8/9] Configuring Caddy reverse proxy..."
  install_caddy
  write_caddyfile "$DOMAIN" "localhost:${DEFAULT_PORT}"

  step "[9/9] Configuring security..."
  setup_firewall
  setup_fail2ban
  setup_ssh

  print_summary "$DOMAIN" "$SERVICE_NAME" \
    "Password : ${password}" \
    "Creds    : ${NEXACORE_BASE_DIR}/configs/${SERVICE_NAME}/credentials.txt" \
    "Compose  : ${APP_DIR}/docker-compose.yml"
}

main "$@"
