#!/usr/bin/env bash
#
# init.sh — One-command setup for the Firehose monorepo.
# Installs deps, sets up the DB, builds JS assets, and runs tests.
#
set -euo pipefail

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

info()    { echo -e "${CYAN}[INFO]${NC}  $*"; }
ok()      { echo -e "${GREEN}[  OK  ]${NC}  $*"; }
warn()    { echo -e "${YELLOW}[ WARN ]${NC}  $*"; }
fail()    { echo -e "${RED}[ FAIL ]${NC}  $*"; }

# ── Pre-flight checks ──────────────────────────────────────────────

missing=()

for cmd in elixir mix node npm; do
  command -v "$cmd" &>/dev/null || missing+=("$cmd")
done

if [ ${#missing[@]} -gt 0 ]; then
  fail "Missing required tools: ${missing[*]}"
  echo "Install them via mise (mise install) or your package manager."
  exit 1
fi

# Check for PostgreSQL
if ! pg_isready &>/dev/null; then
  fail "PostgreSQL is not running or not reachable on localhost."
  echo "Start it with: brew services start postgresql  (or equivalent)"
  exit 1
fi

# ── 1. Get Elixir dependencies ─────────────────────────────────────

info "Fetching Elixir dependencies ..."
make deps
ok "Dependencies fetched."

# ── 2. Set up the database ─────────────────────────────────────────

info "Setting up the database (create + migrate + seed) ..."
cd app && mise exec -- mix ecto.setup
ok "Database ready."
cd ..

# ── 3. Install npm dependencies for assets ─────────────────────────

info "Installing npm dependencies in assets/ ..."
cd app/assets
# Use a temp cache dir to avoid root-owned-file issues in ~/.npm
npm install --cache /tmp/pi-npm-cache 2>/dev/null || npm install
cd ../..
ok "npm dependencies installed."

# ── 4. Build JS assets ─────────────────────────────────────────────

info "Building JS assets ..."
cd app && mise exec -- mix assets.setup && mise exec -- mix assets.build
ok "JS assets built."
cd ..

# ── 5. Run tests ───────────────────────────────────────────────────

info "Running tests ..."
make test
ok "All tests passed."

# ── Done ───────────────────────────────────────────────────────────

echo ""
echo "=============================================="
echo "  🎉 Firehose is ready to go!"
echo "=============================================="
echo ""
echo "  Useful commands:"
echo ""
echo "    make test          Run the full test suite"
echo "    make check         Static analysis (credo + format)"
echo "    make compile       Compile the project"
echo "    make format        Format all code"
echo ""
echo "  Start the dev server:"
echo ""
echo "    cd app && mix phx.server"
echo ""
echo "  The server will be on:  http://localhost:8056"
echo ""
echo "  Demo user (created by seed):"
echo "    email:  demo@example.com"
echo "    pass:   password123!"
echo ""
echo "  Database:  firehose_dev  (PostgreSQL on localhost)"
echo ""
echo "  Port:      8056  (override with PORT=xxxx)"
echo ""
echo "=============================================="
