#!/usr/bin/env bash
#
# FC Foz Platform — one-shot setup for macOS / Linux.
# Installs missing prerequisites (Node.js + Docker), prepares env files, builds
# & starts the backend + database in Docker, and installs frontend dependencies.
#
set -euo pipefail

# Always run from the repository root (the directory of this script).
cd "$(dirname "$0")"

bold() { printf "\033[1m%s\033[0m\n" "$1"; }
info() { printf "  \033[36m➜\033[0m %s\n" "$1"; }
ok()   { printf "  \033[32m✓\033[0m %s\n" "$1"; }
warn() { printf "  \033[33m!\033[0m %s\n" "$1"; }
err()  { printf "  \033[31m✗\033[0m %s\n" "$1" >&2; }

OS="$(uname -s)"
have() { command -v "$1" >/dev/null 2>&1; }

# Run a command with sudo when not already root.
SUDO=""
if [ "$(id -u)" -ne 0 ]; then
  if have sudo; then SUDO="sudo"; fi
fi

bold "FC Foz Platform — setup"
echo

# --- Node.js ---------------------------------------------------------------
install_node() {
  bold "Installing Node.js"
  case "$OS" in
    Darwin)
      if ! have brew; then
        info "Installing Homebrew…"
        /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"
        # Make brew available in this shell (Apple Silicon vs Intel paths).
        eval "$(/opt/homebrew/bin/brew shellenv 2>/dev/null || /usr/local/bin/brew shellenv)"
      fi
      brew install node
      ;;
    Linux)
      if have apt-get; then
        curl -fsSL https://deb.nodesource.com/setup_20.x | $SUDO -E bash -
        $SUDO apt-get install -y nodejs
      elif have dnf; then
        curl -fsSL https://rpm.nodesource.com/setup_20.x | $SUDO -E bash -
        $SUDO dnf install -y nodejs
      elif have pacman; then
        $SUDO pacman -Sy --noconfirm nodejs npm
      else
        err "No supported package manager (apt/dnf/pacman). Install Node 18+ manually: https://nodejs.org"
        return 1
      fi
      ;;
    *)
      err "Unsupported OS '$OS'. Install Node 18+ manually: https://nodejs.org"
      return 1
      ;;
  esac
}

if have npm; then
  ok "Node.js is available ($(node --version 2>/dev/null || echo '?'))"
else
  install_node && ok "Node.js installed" || warn "Node install failed — the frontend step will be skipped"
fi

# --- Docker ----------------------------------------------------------------
install_docker() {
  bold "Installing Docker"
  case "$OS" in
    Darwin)
      # Colima gives a full Docker engine with no GUI / license first-run.
      if ! have brew; then
        err "Homebrew is required to install Docker on macOS."
        return 1
      fi
      brew install colima docker docker-compose
      info "Starting Colima (Docker engine)…"
      colima start
      ;;
    Linux)
      # Docker's official convenience script covers all major distros.
      curl -fsSL https://get.docker.com | $SUDO sh
      $SUDO systemctl enable --now docker 2>/dev/null || true
      # Let the current user run docker without sudo.
      if [ -n "${SUDO}" ]; then
        $SUDO usermod -aG docker "$USER" || true
        warn "Added '$USER' to the 'docker' group — a re-login may be needed for it to take effect."
      fi
      ;;
    *)
      err "Unsupported OS '$OS'. Install Docker manually: https://docs.docker.com/get-docker/"
      return 1
      ;;
  esac
}

if have docker && docker info >/dev/null 2>&1; then
  ok "Docker is available"
else
  if ! have docker; then
    install_docker || { err "Docker install failed."; exit 1; }
  fi
  # Re-check the daemon; on Linux the group change may require sudo for now.
  if ! docker info >/dev/null 2>&1; then
    if $SUDO docker info >/dev/null 2>&1; then
      warn "Docker needs elevated rights this session — using sudo for compose."
      DOCKER_SUDO="$SUDO"
    else
      err "Docker is installed but the daemon is not reachable. Start it and re-run."
      exit 1
    fi
  fi
fi
DOCKER_SUDO="${DOCKER_SUDO:-}"

# Resolve the compose command (plugin vs standalone).
if $DOCKER_SUDO docker compose version >/dev/null 2>&1; then
  COMPOSE="$DOCKER_SUDO docker compose"
elif have docker-compose; then
  COMPOSE="$DOCKER_SUDO docker-compose"
else
  err "Docker Compose was not found."
  exit 1
fi
ok "Docker Compose is available"

# --- Env files -------------------------------------------------------------
echo
bold "Preparing environment files"
if [ ! -f .env ] && [ -f .env.example ]; then
  cp .env.example .env; ok "created .env (root, compose overrides)"
else
  info ".env already present or no example — skipping root env"
fi
if [ ! -f frontend/.env ] && [ -f frontend/.env.example ]; then
  cp frontend/.env.example frontend/.env; ok "created frontend/.env"
else
  info "frontend/.env already present — skipping"
fi

# --- Backend + database ----------------------------------------------------
echo
bold "Building & starting backend + database (Docker)"
$COMPOSE up -d --build
ok "backend on http://localhost:4000  ·  MongoDB on localhost:27018"

# --- Frontend --------------------------------------------------------------
if have npm; then
  echo
  bold "Installing frontend dependencies"
  npm install --prefix frontend
  ok "frontend dependencies installed"
else
  warn "npm not available — skipped frontend dependencies"
fi

# --- Done ------------------------------------------------------------------
echo
bold "Setup complete."
echo
info "Start the frontend:   cd frontend && npm run dev   (http://localhost:8080)"
info "Default admin login:  admin@foz.pt / admin123"
info "Stop everything:      $COMPOSE down"
