#!/bin/bash

# HLS Transcoding Setup Script
# This script initializes the HLS transcoding infrastructure

set -e

echo "==========================================="
echo "HLS Transcoding Setup Script"
echo "==========================================="
echo ""

# Colors for output
GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
NC='\033[0m' # No Color

# Check if .env file exists
if [ ! -f .env ]; then
    echo -e "${YELLOW}⚠ .env file not found${NC}"
    echo "Creating .env from .env.example..."
    cp .env.example .env
    echo -e "${GREEN}✓ .env file created${NC}"
    echo ""
    echo -e "${YELLOW}Please edit .env and configure your settings before proceeding${NC}"
    echo ""
fi

echo -e "${BLUE}Step 1: Checking prerequisites${NC}"

# Check if Docker is installed
if ! command -v docker &> /dev/null; then
    echo -e "${YELLOW}✗ Docker is not installed${NC}"
    echo "Please install Docker from https://www.docker.com/products/docker-desktop"
    exit 1
fi
echo -e "${GREEN}✓ Docker is installed${NC}"

# Check if Docker Compose is installed
if ! command -v docker-compose &> /dev/null; then
    echo -e "${YELLOW}✗ Docker Compose is not installed${NC}"
    echo "Please install Docker Compose or use 'docker compose'"
    exit 1
fi
echo -e "${GREEN}✓ Docker Compose is installed${NC}"

# Check if Node.js is installed
if ! command -v node &> /dev/null; then
    echo -e "${YELLOW}⚠ Node.js is not installed (optional for dev mode)${NC}"
else
    echo -e "${GREEN}✓ Node.js is installed ($(node --version))${NC}"
fi

echo ""
echo -e "${BLUE}Step 2: Creating required directories${NC}"

# Create uploads directory structure
if [ -n "$UPLOADS_PATH" ]; then
    UPLOADS_DIR="$UPLOADS_PATH"
else
    UPLOADS_DIR="/mnt/tank/apps/college-platform/uploads"
fi

mkdir -p "$UPLOADS_DIR/videos"
mkdir -p "$UPLOADS_DIR/hls"
sudo chown -R 1000:1000 "$UPLOADS_DIR" 2>/dev/null || true
chmod -R 755 "$UPLOADS_DIR"

echo -e "${GREEN}✓ Created $UPLOADS_DIR/videos${NC}"
echo -e "${GREEN}✓ Created $UPLOADS_DIR/hls${NC}"

# Create PostgreSQL data directory
if [ -n "$POSTGRES_DATA_PATH" ]; then
    PG_DIR="$POSTGRES_DATA_PATH"
else
    PG_DIR="/mnt/tank/apps/college-platform/postgres_data"
fi

mkdir -p "$PG_DIR"
chmod 700 "$PG_DIR"

echo -e "${GREEN}✓ Created PostgreSQL data directory${NC}"

echo ""
echo -e "${BLUE}Step 3: Building Docker images${NC}"

# Build the transcoder image
docker-compose build transcoder 2>&1 | tail -20
echo -e "${GREEN}✓ Transcoder image built${NC}"

echo ""
echo -e "${BLUE}Step 4: Starting services${NC}"

# Start all services
docker-compose up -d

echo -e "${GREEN}✓ Services started${NC}"

echo ""
echo -e "${BLUE}Step 5: Waiting for services to be ready${NC}"

# Wait for PostgreSQL
echo "Waiting for PostgreSQL..."
for i in {1..30}; do
    if docker-compose exec -T postgres pg_isready -U cms_user &> /dev/null; then
        echo -e "${GREEN}✓ PostgreSQL is ready${NC}"
        break
    fi
    echo -n "."
    sleep 1
done

# Wait for CMS
echo "Waiting for CMS application..."
for i in {1..60}; do
    if docker-compose exec -T cms wget --quiet --spider http://localhost:3000 2>/dev/null; then
        echo -e "${GREEN}✓ CMS is ready${NC}"
        break
    fi
    echo -n "."
    sleep 1
done

# Run Prisma migration
echo ""
echo -e "${BLUE}Step 6: Running database migration${NC}"

docker-compose exec -T cms npx prisma migrate deploy

echo -e "${GREEN}✓ Database migration completed${NC}"

echo ""
echo "==========================================="
echo -e "${GREEN}Setup Complete!${NC}"
echo "==========================================="
echo ""
echo "Services are now running:"
echo "  • CMS: http://localhost:3000"
echo "  • PostgreSQL: localhost:5432"
echo "  • Transcoder: (background service)"
echo ""
echo "Next steps:"
echo "  1. Visit http://localhost:3000 and sign in"
echo "  2. Upload MP4 files as an admin user"
echo "  3. Watch the transcoder logs: docker-compose logs -f transcoder"
echo "  4. Check HLS files: ls -la $UPLOADS_DIR/hls/{video_id}/"
echo ""
echo "For more information, see TRANSCODING.md"
echo ""
