#!/bin/bash
# =============================================================================
# Frontend Build and Deploy Script
# =============================================================================
# Builds the React frontend and deploys to Apache document root
# Run from: /opt/video-accessibility/
# Usage: ./scripts/build-frontend.sh
# =============================================================================

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
PROJECT_DIR="/opt/video-accessibility"
FRONTEND_DIR="$PROJECT_DIR/frontend"
DEPLOY_DIR="/var/www/html/video-accessibility"

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

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

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

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

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

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

preflight_checks() {
  print_header "Pre-flight Checks"

  # Check if frontend directory exists
  if [ ! -d "$FRONTEND_DIR" ]; then
    print_error "Frontend directory not found at $FRONTEND_DIR"
    exit 1
  fi
  print_success "Frontend directory found"

  # Check if package.json exists
  if [ ! -f "$FRONTEND_DIR/package.json" ]; then
    print_error "package.json not found in frontend directory"
    exit 1
  fi
  print_success "package.json found"

  # Check if .env.production exists
  if [ ! -f "$FRONTEND_DIR/.env.production" ]; then
    print_error ".env.production not found in frontend directory"
    print_info "Creating .env.production from template..."
    cp "$FRONTEND_DIR/.env.example" "$FRONTEND_DIR/.env.production" || exit 1
    print_info "Please edit $FRONTEND_DIR/.env.production and run again"
    exit 1
  fi
  print_success ".env.production found"

  # Check if Node.js is installed
  if ! command -v node &> /dev/null; then
    print_error "Node.js is not installed"
    exit 1
  fi
  print_success "Node.js $(node --version) is installed"

  # Check if npm is installed
  if ! command -v npm &> /dev/null; then
    print_error "npm is not installed"
    exit 1
  fi
  print_success "npm $(npm --version) is installed"

  echo ""
}

# =============================================================================
# Build Frontend
# =============================================================================

build_frontend() {
  print_header "Building Frontend"

  cd "$FRONTEND_DIR"

  # Install dependencies (including dev dependencies needed for build)
  print_info "Installing dependencies..."
  npm ci
  print_success "Dependencies installed"

  # Build the application
  print_info "Building React application (this may take a minute)..."
  npm run build
  print_success "Build completed"

  # Check if dist directory was created
  if [ ! -d "dist" ]; then
    print_error "Build failed - dist directory not found"
    exit 1
  fi
  print_success "Build artifacts created in dist/"

  # Display build size
  BUILD_SIZE=$(du -sh dist | cut -f1)
  print_info "Build size: $BUILD_SIZE"

  cd "$PROJECT_DIR"
  echo ""
}

# =============================================================================
# Deploy to Apache
# =============================================================================

deploy_to_apache() {
  print_header "Deploying to Apache"

  # Create deployment directory if it doesn't exist
  print_info "Creating deployment directory..."
  sudo mkdir -p "$DEPLOY_DIR"
  print_success "Deployment directory ready"

  # Clear deployment directory
  print_info "Clearing deployment directory..."
  sudo rm -rf "$DEPLOY_DIR"/*
  print_success "Deployment directory cleared"

  # Copy build artifacts
  print_info "Copying build artifacts..."
  sudo cp -r "$FRONTEND_DIR/dist"/* "$DEPLOY_DIR"/
  print_success "Build artifacts copied"

  # Set proper ownership
  print_info "Setting file ownership to www-data..."
  sudo chown -R www-data:www-data "$DEPLOY_DIR"
  print_success "Ownership set"

  # Set proper permissions
  print_info "Setting file permissions..."
  sudo find "$DEPLOY_DIR" -type d -exec chmod 755 {} \;
  sudo find "$DEPLOY_DIR" -type f -exec chmod 644 {} \;
  print_success "Permissions set"

  echo ""
}

# =============================================================================
# Verify Deployment
# =============================================================================

verify_deployment() {
  print_header "Verifying Deployment"

  # Check if index.html exists
  if [ ! -f "$DEPLOY_DIR/index.html" ]; then
    print_error "index.html not found in deployment directory!"
    exit 1
  fi
  print_success "index.html found"

  # Check if assets directory exists
  if [ ! -d "$DEPLOY_DIR/assets" ]; then
    print_error "assets/ directory not found in deployment!"
    exit 1
  fi
  print_success "assets/ directory found"

  # Count files in deployment
  FILE_COUNT=$(find "$DEPLOY_DIR" -type f | wc -l)
  print_info "Total files deployed: $FILE_COUNT"

  # Display deployment size
  DEPLOY_SIZE=$(sudo du -sh "$DEPLOY_DIR" | cut -f1)
  print_info "Deployment size: $DEPLOY_SIZE"

  echo ""
}

# =============================================================================
# Display Summary
# =============================================================================

display_summary() {
  print_header "Deployment Summary"

  echo -e "${GREEN}Frontend successfully deployed!${NC}"
  echo ""
  echo "Deployment location: $DEPLOY_DIR"
  echo "Frontend URL: https://optical-dev.oliver.solutions/video-accessibility"
  echo ""
  echo "To verify the deployment, visit the URL above in your browser."
  echo ""
}

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

main() {
  print_header "Frontend Build & Deploy"
  echo ""

  preflight_checks
  build_frontend
  deploy_to_apache
  verify_deployment
  display_summary
}

# Run main function
main
