#!/bin/bash
# ═══════════════════════════════════════════════════════
# TheKetoBay — Production Deployment Script
# Usage: ./deploy.sh
# ═══════════════════════════════════════════════════════

set -e
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

echo -e "${GREEN}🥑 TheKetoBay Deployment Script${NC}"
echo "======================================"

# Check .env exists
if [ ! -f .env ]; then
  echo -e "${RED}❌ .env file not found!${NC}"
  echo "Run: cp .env.example .env && nano .env"
  exit 1
fi

echo -e "${YELLOW}📦 Pulling latest changes...${NC}"
git pull origin main 2>/dev/null || echo "Not a git repo, skipping pull."

echo -e "${YELLOW}🐳 Building Docker images...${NC}"
docker compose -f infrastructure/docker-compose.yml build --no-cache api web bot

echo -e "${YELLOW}🔄 Starting services...${NC}"
docker compose -f infrastructure/docker-compose.yml up -d postgres redis

echo -e "${YELLOW}⏳ Waiting for database...${NC}"
sleep 5

echo -e "${YELLOW}🗄️  Running database migrations...${NC}"
docker compose -f infrastructure/docker-compose.yml run --rm api sh -c "cd packages/db && npx prisma migrate deploy"

echo -e "${YELLOW}🌱 Running seed (if first deploy)...${NC}"
docker compose -f infrastructure/docker-compose.yml run --rm api sh -c "cd packages/db && npx prisma db seed" || echo "Seed skipped (already seeded)"

echo -e "${YELLOW}🚀 Starting all services...${NC}"
docker compose -f infrastructure/docker-compose.yml up -d

echo -e "${YELLOW}🤖 Pulling Ollama model (this may take a while)...${NC}"
docker exec ketobay_ollama ollama pull llama3:8b || echo "Model already pulled or GPU not available"

echo ""
echo -e "${GREEN}✅ Deployment complete!${NC}"
echo "======================================"
echo -e "🌐 Website:  ${GREEN}https://theketobay.com${NC}"
echo -e "🔧 API:      ${GREEN}http://localhost:3001/health${NC}"
echo -e "🤖 Ollama:   ${GREEN}http://localhost:11434${NC}"
echo ""
echo -e "👤 Admin:    admin@theketobay.com"
echo -e "🔑 Password: (set in your seed or .env)"
echo ""
echo "Run 'docker compose -f infrastructure/docker-compose.yml logs -f' to monitor logs"
