#!/bin/bash
# =============================================================================
# Local Development Startup Script for Accessible Video Platform
# =============================================================================
# This script starts backend services (API, Worker, MongoDB, Redis) in Docker
# Frontend should be run separately: cd frontend && npm run dev
#
# Usage: ./scripts/run-local.sh [options]
# Options:
#   --rebuild    Force rebuild of Docker images
#   --stop       Stop all services
#   --restart    Restart all services
# =============================================================================

set -e  # Exit on any error

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

# Configuration
COMPOSE_FILES="-f docker-compose.yml -f docker-compose.local.yml --env-file .env.local"

# =============================================================================
# Helper Functions
# =============================================================================

print_header() {
  echo -e "${BLUE}==============================================================================${NC}"
  echo -e "${BLUE}$1${NC}"
  echo -e "${BLUE}==============================================================================${NC}"
}

print_success() {
  echo -e "${GREEN}✓ $1${NC}"
}

print_error() {
  echo -e "${RED}✗ $1${NC}"
}

print_warning() {
  echo -e "${YELLOW}⚠ $1${NC}"
}

print_info() {
  echo -e "${BLUE}ℹ $1${NC}"
}

# =============================================================================
# Pre-flight Checks
# =============================================================================

preflight_checks() {
  print_header "Pre-flight Checks"

  # Check if running from correct directory
  if [ ! -f "docker-compose.yml" ]; then
    print_error "docker-compose.yml not found. Please run from project root."
    exit 1
  fi
  print_success "Running from correct directory"

  # Check if .env.local exists
  if [ ! -f ".env.local" ]; then
    print_error ".env.local not found. Please create it first."
    print_info "You can copy from .env.prod.example and modify for local settings"
    exit 1
  fi
  print_success ".env.local found"

  # Check if secrets directory exists
  if [ ! -d "secrets" ]; then
    print_error "secrets/ directory not found"
    exit 1
  fi
  print_success "secrets/ directory found"

  # Check if GCP credentials exist
  if [ ! -f "secrets/gcp-credentials.json" ]; then
    print_error "secrets/gcp-credentials.json not found"
    exit 1
  fi
  print_success "GCP credentials found"

  # Check if Docker is running
  if ! docker info > /dev/null 2>&1; then
    print_error "Docker is not running"
    exit 1
  fi
  print_success "Docker is running"

  # Check if docker compose is available
  if ! docker compose version &> /dev/null; then
    print_error "docker compose is not installed"
    exit 1
  fi
  print_success "docker compose is available"

  echo ""
}

# =============================================================================
# Stop Services
# =============================================================================

stop_services() {
  print_header "Stopping Services"

  print_info "Stopping all containers..."
  docker compose $COMPOSE_FILES down
  print_success "Services stopped"

  echo ""
}

# =============================================================================
# Start Services
# =============================================================================

start_services() {
  print_header "Starting Local Development Services"

  # Load environment variables
  export $(cat .env.local | grep -v '^#' | xargs)

  # Build images if needed
  if [ "$REBUILD" = true ]; then
    print_info "Building Docker images (--rebuild flag specified)..."
    docker compose $COMPOSE_FILES build --no-cache
    print_success "Docker images built"
  fi

  # Start services
  print_info "Starting services..."
  docker compose $COMPOSE_FILES up -d
  print_success "Services started"

  # Wait for services to be healthy
  print_info "Waiting for services to be healthy (30 seconds)..."
  sleep 30

  # Check service health
  print_info "Checking container status..."
  docker compose $COMPOSE_FILES ps

  echo ""
}

# =============================================================================
# Display Status and Instructions
# =============================================================================

display_status() {
  print_header "Local Development Environment Ready"

  echo -e "${GREEN}✓ Backend services are running in Docker${NC}"
  echo ""
  echo -e "${BLUE}Service URLs:${NC}"
  echo "  API:     http://localhost:8003"
  echo "  Docs:    http://localhost:8003/docs"
  echo "  MongoDB: mongodb://localhost:27017"
  echo "  Redis:   redis://localhost:6379"
  echo ""
  echo -e "${YELLOW}Next Steps:${NC}"
  echo "  1. Start the frontend:"
  echo "     ${GREEN}cd frontend && npm run dev${NC}"
  echo ""
  echo "  2. Access the application:"
  echo "     ${GREEN}http://localhost:6001/video-accessibility${NC}"
  echo ""
  echo -e "${BLUE}Useful Commands:${NC}"
  echo "  View logs:       ${GREEN}docker compose logs -f [service]${NC}"
  echo "  Restart service: ${GREEN}docker compose restart [service]${NC}"
  echo "  Stop services:   ${GREEN}./scripts/run-local.sh --stop${NC}"
  echo "  Rebuild images:  ${GREEN}./scripts/run-local.sh --rebuild${NC}"
  echo ""
  echo -e "${BLUE}Available services:${NC} api, worker, mongodb, redis"
  echo ""
}

# =============================================================================
# Main Function
# =============================================================================

main() {
  # Parse command line arguments
  REBUILD=false
  STOP=false
  RESTART=false

  while [[ $# -gt 0 ]]; do
    case $1 in
      --rebuild)
        REBUILD=true
        shift
        ;;
      --stop)
        STOP=true
        shift
        ;;
      --restart)
        RESTART=true
        shift
        ;;
      *)
        print_error "Unknown option: $1"
        echo "Usage: $0 [--rebuild] [--stop] [--restart]"
        exit 1
        ;;
    esac
  done

  print_header "Accessible Video Platform - Local Development"
  echo ""

  # Execute based on flags
  if [ "$STOP" = true ]; then
    preflight_checks
    stop_services
    print_success "Local development environment stopped"
    exit 0
  fi

  if [ "$RESTART" = true ]; then
    preflight_checks
    stop_services
    start_services
    display_status
    exit 0
  fi

  # Normal startup
  preflight_checks
  start_services
  display_status
}

# Run main function
main "$@"
