#!/bin/bash

###############################################################################
# AdHub Legacy SDK - Deployment Script
#
# Questo script deploya automaticamente:
# 1. SDK Legacy (parser + loader)
# 2. Bundle AdHub Legacy (da lib_adhubmedia)
#
# Usage:
#   ./deploy.sh [production|staging|test]
#
###############################################################################

set -e  # Exit on error

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

# Configuration
PROJECT_ROOT="/var/www/html/adhub_prod"
SDK_SOURCE="$PROJECT_ROOT/sdk_legacy/dist"
BUNDLE_SOURCE="$PROJECT_ROOT/lib_adhubmedia/dist/legacy_adhubmedia"

# Default environment
ENV="${1:-production}"

# Target directories based on environment
case "$ENV" in
  production)
    TARGET_SDK="/var/www/html/lib.adhubmedia.com/sdk"
    TARGET_BUNDLE="/var/www/html/lib.adhubmedia.com/dist/legacy_adhubmedia"
    ;;
  staging)
    TARGET_SDK="/var/www/html/staging.lib.adhubmedia.com/sdk"
    TARGET_BUNDLE="/var/www/html/staging.lib.adhubmedia.com/dist/legacy_adhubmedia"
    ;;
  test|local)
    TARGET_SDK="/var/www/html/test/sdk"
    TARGET_BUNDLE="/var/www/html/test/dist/legacy_adhubmedia"
    ;;
  *)
    echo -e "${RED}❌ Environment non valido: $ENV${NC}"
    echo "Usage: $0 [production|staging|test]"
    exit 1
    ;;
esac

###############################################################################
# Functions
###############################################################################

print_header() {
  echo -e "${BLUE}"
  echo "╔═══════════════════════════════════════════════════════════════╗"
  echo "║                                                               ║"
  echo "║          AdHub Legacy SDK - Deployment Script                ║"
  echo "║                                                               ║"
  echo "╚═══════════════════════════════════════════════════════════════╝"
  echo -e "${NC}"
}

print_section() {
  echo -e "\n${YELLOW}▶ $1${NC}\n"
}

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

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

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

check_files() {
  print_section "Verifica Files Sorgenti"

  # Check SDK files
  if [ ! -f "$SDK_SOURCE/sdk.min.js" ]; then
    print_error "sdk.min.js non trovato in $SDK_SOURCE"
    echo "Esegui prima: npm run build"
    exit 1
  fi
  print_success "sdk.min.js trovato"

  # Check bundle files
  if [ ! -f "$BUNDLE_SOURCE/adhub-legacy_adhubmedia-no-cmp.min.js" ]; then
    print_error "Bundle AdHub non trovato in $BUNDLE_SOURCE"
    echo "Esegui prima il build in lib_adhubmedia"
    exit 1
  fi
  print_success "Bundle AdHub trovato"
}

create_directories() {
  print_section "Creazione Directory Target"

  mkdir -p "$TARGET_SDK"
  print_success "Directory SDK: $TARGET_SDK"

  mkdir -p "$TARGET_BUNDLE"
  print_success "Directory Bundle: $TARGET_BUNDLE"
}

backup_existing() {
  print_section "Backup Files Esistenti"

  local BACKUP_DIR="$TARGET_SDK/../backups/$(date +%Y%m%d_%H%M%S)"

  if [ -f "$TARGET_SDK/sdk.min.js" ]; then
    mkdir -p "$BACKUP_DIR/sdk"
    cp "$TARGET_SDK"/*.js "$BACKUP_DIR/sdk/" 2>/dev/null || true
    print_success "Backup SDK: $BACKUP_DIR/sdk"
  fi

  if [ -f "$TARGET_BUNDLE/adhub-legacy_adhubmedia-no-cmp.min.js" ]; then
    mkdir -p "$BACKUP_DIR/bundle"
    cp "$TARGET_BUNDLE"/*.js "$BACKUP_DIR/bundle/" 2>/dev/null || true
    print_success "Backup Bundle: $BACKUP_DIR/bundle"
  fi
}

deploy_sdk() {
  print_section "Deploy SDK Legacy"

  # Copy JS files
  cp "$SDK_SOURCE/sdk.min.js" "$TARGET_SDK/"
  print_success "Copiato: sdk.min.js"

  cp "$SDK_SOURCE/sdk.js" "$TARGET_SDK/"
  print_success "Copiato: sdk.js"

  # Copy .htaccess
  if [ -f "$SDK_SOURCE/.htaccess" ]; then
    cp "$SDK_SOURCE/.htaccess" "$TARGET_SDK/"
    print_success "Copiato: .htaccess"
  fi

  # Set permissions
  chmod 644 "$TARGET_SDK"/*.js
  if [ -f "$TARGET_SDK/.htaccess" ]; then
    chmod 644 "$TARGET_SDK/.htaccess"
  fi
  print_success "Permessi impostati (644)"
}

deploy_bundle() {
  print_section "Deploy Bundle AdHub Legacy"

  # Copy all JS files
  cp "$BUNDLE_SOURCE"/*.js "$TARGET_BUNDLE/"
  print_success "Copiati: *.js files"

  # Copy txt files (integration guides, ads.txt)
  cp "$BUNDLE_SOURCE"/*.txt "$TARGET_BUNDLE/" 2>/dev/null || true
  print_success "Copiati: *.txt files"

  # Set permissions
  chmod 644 "$TARGET_BUNDLE"/*.js
  chmod 644 "$TARGET_BUNDLE"/*.txt 2>/dev/null || true
  print_success "Permessi impostati (644)"
}

verify_deployment() {
  print_section "Verifica Deployment"

  # Check SDK
  if [ -f "$TARGET_SDK/sdk.min.js" ]; then
    local SDK_SIZE=$(du -h "$TARGET_SDK/sdk.min.js" | cut -f1)
    print_success "SDK deployed: $SDK_SIZE"
  else
    print_error "SDK non trovato in target!"
    exit 1
  fi

  # Check Bundle
  if [ -f "$TARGET_BUNDLE/adhub-legacy_adhubmedia-no-cmp.min.js" ]; then
    local BUNDLE_SIZE=$(du -h "$TARGET_BUNDLE/adhub-legacy_adhubmedia-no-cmp.min.js" | cut -f1)
    print_success "Bundle deployed: $BUNDLE_SIZE"
  else
    print_error "Bundle non trovato in target!"
    exit 1
  fi
}

print_summary() {
  print_section "Summary"

  echo -e "${GREEN}"
  echo "╔═══════════════════════════════════════════════════════════════╗"
  echo "║                    ✅ DEPLOYMENT SUCCESS                      ║"
  echo "╚═══════════════════════════════════════════════════════════════╝"
  echo -e "${NC}"

  print_info "Environment: $ENV"
  print_info "SDK Location: $TARGET_SDK"
  print_info "Bundle Location: $TARGET_BUNDLE"

  echo ""
  print_info "URLs Finali:"
  case "$ENV" in
    production)
      echo "  • SDK: https://lib.adhubmedia.com/sdk/sdk.min.js"
      echo "  • Bundle: https://lib.adhubmedia.com/dist/legacy_adhubmedia/adhub-legacy_adhubmedia-no-cmp.min.js"
      ;;
    staging)
      echo "  • SDK: https://staging.lib.adhubmedia.com/sdk/sdk.min.js"
      echo "  • Bundle: https://staging.lib.adhubmedia.com/dist/legacy_adhubmedia/adhub-legacy_adhubmedia-no-cmp.min.js"
      ;;
    test)
      echo "  • SDK: file://$TARGET_SDK/sdk.min.js"
      echo "  • Bundle: file://$TARGET_BUNDLE/adhub-legacy_adhubmedia-no-cmp.min.js"
      ;;
  esac

  echo ""
  print_info "Next Steps:"
  echo "  1. Test URL con curl -I"
  echo "  2. Verifica CORS headers"
  echo "  3. Test in browser con examples/test.html"
  echo "  4. Clear CDN cache (se presente)"
  echo "  5. Notifica publisher della migrazione"
}

###############################################################################
# Main Execution
###############################################################################

main() {
  print_header

  print_info "Deployment Environment: $ENV"
  print_info "Project Root: $PROJECT_ROOT"
  echo ""

  # Confirm production deployment
  if [ "$ENV" = "production" ]; then
    echo -e "${YELLOW}⚠️  ATTENZIONE: Stai per deployare in PRODUCTION!${NC}"
    read -p "Continuare? (yes/no): " -r
    echo
    if [[ ! $REPLY =~ ^[Yy]es$ ]]; then
      print_error "Deploy annullato"
      exit 1
    fi
  fi

  # Execute deployment steps
  check_files
  create_directories
  backup_existing
  deploy_sdk
  deploy_bundle
  verify_deployment
  print_summary
}

# Run main
main

exit 0
