#!/bin/bash
set -e

# ─── colours ────────────────────────────────────────────────────────────────
RED='\033[0;31m'; GREEN='\033[0;32m'; YELLOW='\033[1;33m'; NC='\033[0m'
info()    { echo -e "${GREEN}[deploy]${NC} $1"; }
warn()    { echo -e "${YELLOW}[warn]${NC}   $1"; }
error()   { echo -e "${RED}[error]${NC}  $1"; exit 1; }

ROOT="$(cd "$(dirname "$0")" && pwd)"

# ─── preflight ──────────────────────────────────────────────────────────────
info "Checking required tools..."
command -v docker   >/dev/null || error "docker not found — install it first"
command -v node     >/dev/null || error "node not found — install it first"
command -v python3  >/dev/null || error "python3 not found — install it first"
command -v pm2      >/dev/null || error "pm2 not found — run: sudo npm install -g pm2"

# ─── env file ───────────────────────────────────────────────────────────────
if [ ! -f "$ROOT/backend/.env" ]; then
  warn "backend/.env not found — copying from .env.example"
  cp "$ROOT/backend/.env.example" "$ROOT/backend/.env"
  warn "Fill in backend/.env with your real values, then re-run this script."
  exit 1
fi

# ─── database ───────────────────────────────────────────────────────────────
info "Starting PostgreSQL via Docker..."
docker compose -f "$ROOT/docker-compose.yml" up -d db

info "Waiting for database to be ready..."
until docker compose -f "$ROOT/docker-compose.yml" exec -T db \
  pg_isready -U aci -d aci_db >/dev/null 2>&1; do
  sleep 1
done
info "Database is ready."

# ─── backend ────────────────────────────────────────────────────────────────
info "Setting up Python virtualenv..."
cd "$ROOT/backend"
python3 -m venv venv
source venv/bin/activate
pip install -q -r requirements.txt

info "Running database migrations..."
alembic upgrade head

info "Starting backend with PM2..."
pm2 delete backend 2>/dev/null || true
pm2 start "venv/bin/uvicorn main:app --host 0.0.0.0 --port 8000" \
  --name backend \
  --cwd "$ROOT/backend"

# ─── frontend ───────────────────────────────────────────────────────────────
info "Installing frontend dependencies..."
cd "$ROOT/frontend"
npm install --silent

info "Building frontend..."
npm run build

info "Starting frontend with PM2..."
pm2 delete frontend 2>/dev/null || true
pm2 start "npm start -- -p 3000" \
  --name frontend \
  --cwd "$ROOT/frontend"

# ─── persist PM2 on reboot ──────────────────────────────────────────────────
info "Saving PM2 process list..."
pm2 save

# ─── done ───────────────────────────────────────────────────────────────────
echo ""
pm2 list
echo ""
info "Deploy complete!"
info "  Frontend → http://$(curl -s ifconfig.me 2>/dev/null || echo '<your-ec2-ip>'):3000"
info "  Backend  → http://$(curl -s ifconfig.me 2>/dev/null || echo '<your-ec2-ip>'):8000"
info ""
info "Useful commands:"
info "  pm2 logs backend    — tail backend logs"
info "  pm2 logs frontend   — tail frontend logs"
info "  pm2 restart all     — restart after a code update"
info "  pm2 startup         — enable autostart on reboot (run once)"
