#!/bin/bash

# Placebo.mk Setup Script
# This script sets up the development environment

set -e

echo "🚀 Setting up Placebo.mk development environment..."

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo "❌ Docker is not installed. Please install Docker first."
    exit 1
fi

# Check if Docker Compose is installed
if ! command -v docker-compose &> /dev/null && ! docker compose version &> /dev/null; then
    echo "❌ Docker Compose is not installed. Please install Docker Compose."
    exit 1
fi

# Check Node.js version
if ! command -v node &> /dev/null; then
    echo "⚠️  Node.js is not installed. Local mode won't work, but Docker mode will."
fi

# Create necessary directories
echo "📁 Creating directories..."
mkdir -p scripts
mkdir -p backend/uploads
mkdir -p cms/cms/public/uploads

# Set up environment files
echo "⚙️  Setting up environment files..."

# Backend
if [ ! -f backend/.env ]; then
    echo "Creating backend/.env from template..."
    cp backend/.env.docker.template backend/.env
fi

if [ ! -f backend/.env.local ]; then
    echo "Creating backend/.env.local from template..."
    cp backend/.env.local.template backend/.env.local
fi

# Frontend
if [ ! -f frontend/.env ]; then
    echo "Creating frontend/.env from template..."
    cp frontend/.env.docker.template frontend/.env
fi

if [ ! -f frontend/.env.local ]; then
    echo "Creating frontend/.env.local from template..."
    cp frontend/.env.local.template frontend/.env.local
fi

# Install root dependencies
echo "📦 Installing root dependencies..."
if command -v npm &> /dev/null; then
    npm install
else
    echo "⚠️  npm not found, skipping root dependencies"
fi

# Build Docker images
echo "🐳 Building Docker images..."
if docker compose version &> /dev/null; then
    docker compose -f docker-compose.dev.yml build
else
    docker-compose -f docker-compose.dev.yml build
fi

echo ""
echo "✅ Setup complete!"
echo ""
echo "Next steps:"
echo "1. Start in Docker mode: npm run docker:up"
echo "2. Or start in local mode:"
echo "   - First terminal: docker-compose -f docker-compose.dev.yml up postgres"
echo "   - Second terminal: npm run dev:local"
echo ""
echo "For more details, see README-DEVELOPMENT.md"