#!/bin/bash

# Vision Videoke Production Configuration Script
set -e

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

log() {
    echo -e "${GREEN}[$(date +'%Y-%m-%d %H:%M:%S')] $1${NC}"
}

error() {
    echo -e "${RED}[ERROR] $1${NC}"
    exit 1
}

warn() {
    echo -e "${YELLOW}[WARNING] $1${NC}"
}

info() {
    echo -e "${BLUE}[INFO] $1${NC}"
}

# Configuration variables
APP_DIR="/var/www/visionvideoke"
ENV_FILE="$APP_DIR/.env"

log "Starting production configuration..."

# Function to prompt for input with default value
prompt_input() {
    local prompt="$1"
    local default="$2"
    local var_name="$3"
    local is_secret="${4:-false}"
    
    if [ "$is_secret" = "true" ]; then
        echo -n "$prompt [$default]: "
        read -s input
        echo ""
    else
        echo -n "$prompt [$default]: "
        read input
    fi
    
    if [ -z "$input" ]; then
        input="$default"
    fi
    
    eval "$var_name='$input'"
}

# Function to generate random string
generate_random() {
    local length=${1:-32}
    openssl rand -hex $length
}

# Function to validate email
validate_email() {
    local email="$1"
    if [[ $email =~ ^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}$ ]]; then
        return 0
    else
        return 1
    fi
}

# Function to validate domain
validate_domain() {
    local domain="$1"
    if [[ $domain =~ ^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9]\.[a-zA-Z]{2,}$ ]]; then
        return 0
    else
        return 1
    fi
}

# Collect configuration information
log "Collecting configuration information..."
echo ""

# Domain configuration
while true; do
    prompt_input "Enter your domain name (e.g., visionvideoke.com)" "localhost" "DOMAIN_NAME"
    if [ "$DOMAIN_NAME" = "localhost" ] || validate_domain "$DOMAIN_NAME"; then
        break
    else
        error "Invalid domain name. Please enter a valid domain."
    fi
done

# SSL Email
while true; do
    prompt_input "Enter email for SSL certificate" "admin@$DOMAIN_NAME" "SSL_EMAIL"
    if validate_email "$SSL_EMAIL"; then
        break
    else
        error "Invalid email address. Please enter a valid email."
    fi
done

# API Keys
echo ""
info "API Keys Configuration (Required for full functionality):"
prompt_input "OpenAI API Key" "your_openai_api_key_here" "OPENAI_API_KEY" true
prompt_input "Udio API Key" "your_udio_api_key_here" "UDIO_API_KEY" true
prompt_input "ElevenLabs API Key" "your_elevenlabs_api_key_here" "ELEVENLABS_API_KEY" true
prompt_input "Veo API Key (optional)" "your_veo_api_key_here" "VEO_API_KEY" true

# Database configuration
echo ""
info "Database Configuration (optional - for user management):"
prompt_input "Database URL" "postgresql://user:password@localhost:5432/visionvideoke" "DATABASE_URL"

# AWS S3 Configuration
echo ""
info "AWS S3 Configuration (for file storage):"
prompt_input "AWS Access Key ID" "your_aws_access_key" "AWS_ACCESS_KEY_ID" true
prompt_input "AWS Secret Access Key" "your_aws_secret_key" "AWS_SECRET_ACCESS_KEY" true
prompt_input "AWS Region" "us-east-1" "AWS_REGION"
prompt_input "S3 Bucket Name" "visionvideoke-uploads" "AWS_S3_BUCKET"

# Security configuration
echo ""
info "Security Configuration:"
JWT_SECRET=$(generate_random 32)
ENCRYPTION_KEY=$(generate_random 32)
info "Generated JWT Secret: ${JWT_SECRET:0:8}..."
info "Generated Encryption Key: ${ENCRYPTION_KEY:0:8}..."

# Payment configuration
echo ""
info "Payment Configuration (Stripe):"
prompt_input "Stripe Publishable Key" "pk_live_your_stripe_key" "STRIPE_PUBLISHABLE_KEY"
prompt_input "Stripe Secret Key" "sk_live_your_stripe_secret" "STRIPE_SECRET_KEY" true

# Monitoring configuration
echo ""
info "Monitoring Configuration (optional):"
prompt_input "Sentry DSN (for error tracking)" "your_sentry_dsn_here" "SENTRY_DSN"

# Create environment file
log "Creating environment file..."
cat > $ENV_FILE <<EOF
# Vision Videoke Production Environment Configuration
# Generated on $(date)

# Application Configuration
NODE_ENV=production
PORT=3000

# Domain Configuration
DOMAIN_NAME=$DOMAIN_NAME
SSL_EMAIL=$SSL_EMAIL

# API Keys
REACT_APP_OPENAI_API_KEY=$OPENAI_API_KEY
REACT_APP_UDIO_API_KEY=$UDIO_API_KEY
REACT_APP_ELEVENLABS_API_KEY=$ELEVENLABS_API_KEY
REACT_APP_VEO_API_KEY=$VEO_API_KEY

# Database Configuration
DATABASE_URL=$DATABASE_URL

# File Storage (AWS S3)
AWS_ACCESS_KEY_ID=$AWS_ACCESS_KEY_ID
AWS_SECRET_ACCESS_KEY=$AWS_SECRET_ACCESS_KEY
AWS_REGION=$AWS_REGION
AWS_S3_BUCKET=$AWS_S3_BUCKET

# Security
JWT_SECRET=$JWT_SECRET
ENCRYPTION_KEY=$ENCRYPTION_KEY

# Payment Processing (Stripe)
REACT_APP_STRIPE_PUBLISHABLE_KEY=$STRIPE_PUBLISHABLE_KEY
STRIPE_SECRET_KEY=$STRIPE_SECRET_KEY

# Monitoring
SENTRY_DSN=$SENTRY_DSN

# Application URLs
REACT_APP_API_URL=https://$DOMAIN_NAME/api
REACT_APP_APP_URL=https://$DOMAIN_NAME

# Feature Flags
REACT_APP_ENABLE_VOICE_CLONING=true
REACT_APP_ENABLE_VIDEO_GENERATION=true
REACT_APP_ENABLE_PAYMENTS=true
REACT_APP_ENABLE_USER_ACCOUNTS=true

# Rate Limiting
RATE_LIMIT_WINDOW_MS=900000
RATE_LIMIT_MAX_REQUESTS=100

# File Upload Limits
MAX_FILE_SIZE=100MB
MAX_FILES_PER_UPLOAD=10

# Session Configuration
SESSION_SECRET=$JWT_SECRET
SESSION_TIMEOUT=86400000

# Email Configuration (for notifications)
SMTP_HOST=smtp.gmail.com
SMTP_PORT=587
SMTP_USER=your_email@gmail.com
SMTP_PASS=your_app_password

# Logging
LOG_LEVEL=info
LOG_FILE=/var/log/visionvideoke/app.log
EOF

# Set proper permissions
chmod 600 $ENV_FILE
chown ec2-user:ec2-user $ENV_FILE

# Create production build configuration
log "Creating production build configuration..."
if [ -d "$APP_DIR" ]; then
    cd $APP_DIR
    
    # Create or update vite.config.js for production
    if [ ! -f "vite.config.js" ]; then
        cat > vite.config.js <<EOF
import { defineConfig } from 'vite'
import react from '@vitejs/plugin-react'

export default defineConfig({
  plugins: [react()],
  build: {
    outDir: 'dist',
    sourcemap: false,
    minify: 'terser',
    rollupOptions: {
      output: {
        manualChunks: {
          vendor: ['react', 'react-dom'],
          router: ['react-router-dom'],
          ui: ['framer-motion', '@heroicons/react'],
          utils: ['axios', 'zustand']
        }
      }
    },
    terserOptions: {
      compress: {
        drop_console: true,
        drop_debugger: true
      }
    }
  },
  server: {
    port: 3000,
    host: '0.0.0.0'
  },
  preview: {
    port: 3000,
    host: '0.0.0.0'
  }
})
EOF
    fi
    
    # Create or update .env.production
    cat > .env.production <<EOF
VITE_API_URL=https://$DOMAIN_NAME/api
VITE_APP_URL=https://$DOMAIN_NAME
VITE_OPENAI_API_KEY=$OPENAI_API_KEY
VITE_UDIO_API_KEY=$UDIO_API_KEY
VITE_ELEVENLABS_API_KEY=$ELEVENLABS_API_KEY
VITE_VEO_API_KEY=$VEO_API_KEY
VITE_STRIPE_PUBLISHABLE_KEY=$STRIPE_PUBLISHABLE_KEY
VITE_ENABLE_VOICE_CLONING=true
VITE_ENABLE_VIDEO_GENERATION=true
VITE_ENABLE_PAYMENTS=true
EOF
    
    chmod 600 .env.production
fi

# Create systemd service for additional monitoring
log "Creating systemd monitoring service..."
sudo tee /etc/systemd/system/visionvideoke-monitor.service > /dev/null <<EOF
[Unit]
Description=Vision Videoke Monitoring Service
After=network.target

[Service]
Type=simple
User=ec2-user
ExecStart=/home/ec2-user/monitor.sh
Restart=always
RestartSec=300

[Install]
WantedBy=multi-user.target
EOF

# Create systemd timer for monitoring
sudo tee /etc/systemd/system/visionvideoke-monitor.timer > /dev/null <<EOF
[Unit]
Description=Run Vision Videoke Monitor every 10 minutes
Requires=visionvideoke-monitor.service

[Timer]
OnCalendar=*:0/10
Persistent=true

[Install]
WantedBy=timers.target
EOF

# Enable monitoring service
sudo systemctl daemon-reload
sudo systemctl enable visionvideoke-monitor.timer
sudo systemctl start visionvideoke-monitor.timer

# Create performance optimization script
log "Creating performance optimization script..."
cat > /home/ec2-user/optimize-performance.sh <<'EOF'
#!/bin/bash

# Performance optimization script for Vision Videoke
log() {
    echo "[$(date +'%Y-%m-%d %H:%M:%S')] $1"
}

log "Starting performance optimization..."

# Optimize Node.js memory settings
export NODE_OPTIONS="--max-old-space-size=2048 --optimize-for-size"

# Set PM2 optimization
pm2 set pm2:autodump true
pm2 set pm2:deep-monitoring true

# Optimize nginx worker processes
WORKER_PROCESSES=$(nproc)
sudo sed -i "s/worker_processes auto;/worker_processes $WORKER_PROCESSES;/" /etc/nginx/nginx.conf

# Enable nginx gzip compression
sudo tee /etc/nginx/conf.d/gzip.conf > /dev/null <<GZIPEOF
gzip on;
gzip_vary on;
gzip_min_length 1024;
gzip_proxied any;
gzip_comp_level 6;
gzip_types
    text/plain
    text/css
    text/xml
    text/javascript
    application/json
    application/javascript
    application/xml+rss
    application/atom+xml
    image/svg+xml;
GZIPEOF

# Optimize system limits
echo "ec2-user soft nofile 65536" | sudo tee -a /etc/security/limits.conf
echo "ec2-user hard nofile 65536" | sudo tee -a /etc/security/limits.conf

# Optimize kernel parameters
sudo tee /etc/sysctl.d/99-visionvideoke.conf > /dev/null <<SYSCTLEOF
# Network optimizations
net.core.somaxconn = 65536
net.core.netdev_max_backlog = 5000
net.ipv4.tcp_max_syn_backlog = 65536
net.ipv4.tcp_keepalive_time = 600
net.ipv4.tcp_keepalive_intvl = 60
net.ipv4.tcp_keepalive_probes = 10

# Memory optimizations
vm.swappiness = 10
vm.dirty_ratio = 15
vm.dirty_background_ratio = 5
SYSCTLEOF

sudo sysctl -p /etc/sysctl.d/99-visionvideoke.conf

# Restart services
sudo systemctl reload nginx
pm2 restart all

log "Performance optimization completed"
EOF

chmod +x /home/ec2-user/optimize-performance.sh

# Create configuration summary
log "Creating configuration summary..."
cat > /home/ec2-user/config-summary.txt <<EOF
Vision Videoke Production Configuration Summary
Generated on $(date)

Domain: $DOMAIN_NAME
SSL Email: $SSL_EMAIL

API Keys Configured:
- OpenAI: ${OPENAI_API_KEY:0:8}...
- Udio: ${UDIO_API_KEY:0:8}...
- ElevenLabs: ${ELEVENLABS_API_KEY:0:8}...
- Veo: ${VEO_API_KEY:0:8}...

AWS S3:
- Region: $AWS_REGION
- Bucket: $AWS_S3_BUCKET

Security:
- JWT Secret: Generated
- Encryption Key: Generated

Payment:
- Stripe: Configured

Files Created:
- Environment: $ENV_FILE
- Build Config: $APP_DIR/vite.config.js
- Production Env: $APP_DIR/.env.production
- Monitoring Service: /etc/systemd/system/visionvideoke-monitor.service

Next Steps:
1. Review and update API keys in $ENV_FILE
2. Configure DNS to point $DOMAIN_NAME to this server
3. Run SSL setup: ./setup-ssl.sh $DOMAIN_NAME
4. Deploy application: ./build-and-deploy.sh
5. Optimize performance: ./optimize-performance.sh
EOF

log "Production configuration completed successfully!"
log ""
log "Configuration Summary:"
log "- Domain: $DOMAIN_NAME"
log "- Environment file: $ENV_FILE"
log "- Configuration summary: /home/ec2-user/config-summary.txt"
log ""
log "IMPORTANT: Please review and update the API keys in $ENV_FILE before deploying!"
log ""
log "Next steps:"
log "1. Update API keys in $ENV_FILE"
log "2. Point your domain to this server's IP"
log "3. Run: ./setup-ssl.sh $DOMAIN_NAME"
log "4. Deploy: ./build-and-deploy.sh"

