#!/usr/bin/env bash
#
# Innovatieplatform — one-command setup for Linux
#
# Usage:  git clone <repo> && cd innovatieplatform && bash setup.sh
#
# Prerequisites: docker, docker compose (v2), git
# Optional: ANTHROPIC_API_KEY for AI chat (can be added later to .env)
#
set -euo pipefail

CYAN='\033[0;36m'
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m'

log()  { echo -e "${CYAN}▸${NC} $1"; }
ok()   { echo -e "${GREEN}✓${NC} $1"; }
fail() { echo -e "${RED}✗${NC} $1"; exit 1; }

# ── Check prerequisites ────────────────────────────────────────────
command -v docker >/dev/null 2>&1 || fail "Docker not found. Install: https://docs.docker.com/engine/install/"
docker compose version >/dev/null 2>&1 || fail "Docker Compose v2 not found."

# ── Create .env if missing ─────────────────────────────────────────
if [ ! -f .env ]; then
    log "Creating .env from .env.example..."
    cp .env.example .env

    # Generate APP_KEY
    APP_KEY=$(docker run --rm -w /app -v "$(pwd)":/app composer:latest php -r "echo 'base64:' . base64_encode(random_bytes(32));")
    sed -i "s|^APP_KEY=.*|APP_KEY=${APP_KEY}|" .env

    # Set app name
    sed -i "s|^APP_NAME=.*|APP_NAME=Innovatieplatform|" .env

    ok ".env created with generated APP_KEY"
else
    ok ".env already exists"
fi

# ── Build and start containers ──────────────────────────────────────
log "Building Docker containers (first run takes a few minutes)..."
docker compose build --quiet

log "Starting services..."
docker compose up -d

# ── Wait for PostgreSQL to be ready ────────────────────────────────
log "Waiting for PostgreSQL..."
for i in $(seq 1 30); do
    if docker compose exec -T postgresql pg_isready -U innovatie -d innovatieplatform >/dev/null 2>&1; then
        ok "PostgreSQL ready"
        break
    fi
    if [ "$i" -eq 30 ]; then fail "PostgreSQL did not start in time"; fi
    sleep 1
done

# ── Wait for Redis ──────────────────────────────────────────────────
log "Waiting for Redis..."
for i in $(seq 1 15); do
    if docker compose exec -T redis redis-cli ping 2>/dev/null | grep -q PONG; then
        ok "Redis ready"
        break
    fi
    if [ "$i" -eq 15 ]; then fail "Redis did not start in time"; fi
    sleep 1
done

# ── Laravel setup inside the container ──────────────────────────────
log "Running migrations and seeding database..."
docker compose exec -T laravel-app php artisan config:clear 2>/dev/null || true
docker compose exec -T laravel-app php artisan migrate:fresh --seed --force

ok "Database migrated and seeded"

# ── Build frontend assets ───────────────────────────────────────────
log "Installing Node.js dependencies and building frontend..."
if command -v npm >/dev/null 2>&1; then
    npm install --silent 2>/dev/null
    npx vite build 2>/dev/null
    ok "Frontend built"
else
    log "npm not found locally — frontend assets may need building"
    log "Run: npm install && npx vite build"
fi

# ── Summary ─────────────────────────────────────────────────────────
echo ""
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
echo -e "${GREEN}  Innovatieplatform is running!${NC}"
echo -e "${GREEN}══════════════════════════════════════════════════${NC}"
echo ""
echo -e "  ${CYAN}App:${NC}        http://localhost"
echo -e "  ${CYAN}Login:${NC}      rene@wbd-rd.nl / password"
echo -e "  ${CYAN}Database:${NC}   postgresql://innovatie:secret@localhost:5432/innovatieplatform"
echo -e "  ${CYAN}AI Service:${NC} http://localhost:8000/health"
echo ""
echo -e "  To enable AI chat: add ${CYAN}ANTHROPIC_API_KEY=sk-ant-...${NC} to .env"
echo -e "  then run: ${CYAN}docker compose restart ai-service${NC}"
echo ""
echo -e "  Stop:    ${CYAN}docker compose down${NC}"
echo -e "  Restart: ${CYAN}docker compose up -d${NC}"
echo -e "  Reseed:  ${CYAN}docker compose exec laravel-app php artisan migrate:fresh --seed${NC}"
echo ""
