# Deployment Requirements Specification

## Overview

Complete deployment guide for AI StyleGallery, including system requirements, dependency management, environment configuration, and operational procedures for production deployment.

## System Requirements

### Server Requirements

#### Minimum Specifications
- **Operating System**: Linux (Ubuntu 20.04+, CentOS 8+, Debian 11+)
- **Web Server**: Apache 2.4+ or Nginx 1.20+
- **Database**: SQLite 3.8+ (default) or MySQL 8.0+/PostgreSQL 13+
- **PHP Version**: 8.3+ with extensions
- **Memory**: 2GB RAM minimum, 4GB recommended
- **Storage**: 10GB minimum, 50GB recommended
- **Network**: Stable internet connection for AI services

#### Recommended Production Setup
- **Operating System**: Ubuntu 22.04 LTS
- **Web Server**: Nginx 1.24+ with PHP-FPM
- **Database**: PostgreSQL 15+ for production workloads
- **Redis**: 7.0+ for caching and sessions
- **SSL/TLS**: Let's Encrypt or commercial certificate

### PHP Requirements

#### Required Extensions
```bash
# Core extensions
php8.3-cli
php8.3-common
php8.3-fpm
php8.3-mysql    # or php8.3-pgsql for PostgreSQL
php8.3-sqlite3
php8.3-redis
php8.3-curl
php8.3-gd
php8.3-mbstring
php8.3-xml
php8.3-zip
php8.3-bcmath
php8.3-intl

# Development extensions (recommended)
php8.3-xdebug  # For development only
```

#### PHP Configuration (`php.ini`)
```ini
# Performance settings
memory_limit = 256M
max_execution_time = 300
max_input_time = 300
upload_max_filesize = 10M
post_max_size = 12M

# Error handling
display_errors = Off
display_startup_errors = Off
error_reporting = E_ALL & ~E_DEPRECATED & ~E_STRICT
log_errors = On
error_log = /var/log/php/error.log

# Security
expose_php = Off
allow_url_fopen = Off
allow_url_include = Off

# Session security
session.cookie_httponly = 1
session.cookie_secure = 1
session.use_strict_mode = 1

# OPcache (recommended for production)
opcache.enable = 1
opcache.memory_consumption = 128
opcache.max_accelerated_files = 10000
opcache.validate_timestamps = 1
```

## Dependency Management

### PHP Dependencies (Composer)

#### Production Dependencies
```json
{
  "require": {
    "php": "^8.3",
    "laravel/framework": "^12.0",
    "laravel/tinker": "^2.10",
    "filament/filament": "^3.3",
    "laravel/sanctum": "^4.0",
    "predis/predis": "^2.0",
    "nesbot/carbon": "^3.0",
    "ramsey/uuid": "^4.0",
    "guzzlehttp/guzzle": "^7.0"
  }
}
```

#### Development Dependencies
```json
{
  "require-dev": {
    "phpunit/phpunit": "^12.0",
    "laravel/pint": "^1.0",
    "laravel/sail": "^1.0",
    "spatie/laravel-ignition": "^2.0",
    "fakerphp/faker": "^1.23",
    "laravel/dusk": "^8.0"
  }
}
```

### Node.js Dependencies (npm/yarn)

#### Production Dependencies
```json
{
  "dependencies": {
    "axios": "^1.11.0",
    "vue": "^3.5.0",
    "@inertiajs/vue3": "^1.3.0",
    "tailwindcss": "^3.4.0",
    "autoprefixer": "^10.4.0",
    "postcss": "^8.5.0",
    "@fortawesome/fontawesome-svg-core": "^7.0.0",
    "@fortawesome/free-solid-svg-icons": "^7.0.0",
    "@fortawesome/vue-fontawesome": "^3.1.0",
    "vanilla-lazyload": "^19.1.0"
  }
}
```

#### Development Dependencies
```json
{
  "devDependencies": {
    "@vitejs/plugin-vue": "^5.2.0",
    "laravel-vite-plugin": "^1.0.0",
    "vite": "^5.4.0",
    "@tailwindcss/forms": "^0.5.0",
    "laravel-echo": "^2.1.0",
    "pusher-js": "^8.4.0"
  }
}
```

## Environment Configuration

### Environment Variables (`.env`)

#### Required Variables
```bash
# Application
APP_NAME="AI StyleGallery"
APP_ENV=production
APP_KEY=base64:your-generated-app-key
APP_DEBUG=false
APP_URL=https://your-domain.com

# Database (SQLite default)
DB_CONNECTION=sqlite
DB_DATABASE=/path/to/storage/database.sqlite

# Alternative Database (MySQL/PostgreSQL)
# DB_CONNECTION=mysql
# DB_HOST=127.0.0.1
# DB_PORT=3306
# DB_DATABASE=ai_stylegallery
# DB_USERNAME=your-db-user
# DB_PASSWORD=your-db-password

# Redis (recommended for production)
REDIS_CLIENT=phpredis
REDIS_HOST=127.0.0.1
REDIS_PASSWORD=null
REDIS_PORT=6379

# Mail Configuration
MAIL_MAILER=smtp
MAIL_HOST=smtp.your-provider.com
MAIL_PORT=587
MAIL_USERNAME=your-email@domain.com
MAIL_PASSWORD=your-app-password
MAIL_ENCRYPTION=tls
MAIL_FROM_ADDRESS=noreply@your-domain.com
MAIL_FROM_NAME="${APP_NAME}"

# Broadcasting (for real-time features)
BROADCAST_CONNECTION=pusher
PUSHER_APP_ID=your-pusher-id
PUSHER_APP_KEY=your-pusher-key
PUSHER_APP_SECRET=your-pusher-secret
PUSHER_HOST=api.pusherapp.com
PUSHER_PORT=443
PUSHER_SCHEME=https
PUSHER_APP_CLUSTER=your-cluster

# Queue (for background processing)
QUEUE_CONNECTION=database

# Filesystem
FILESYSTEM_DISK=local

# Sanctum (API authentication)
SANCTUM_STATEFUL_DOMAINS=your-domain.com
```

#### AI Provider Configuration
```bash
# ComfyUI Configuration
COMFYUI_API_URL=https://your-comfyui-server.com
COMFYUI_API_KEY=your-comfyui-api-key
COMFYUI_TIMEOUT=180
COMFYUI_MAX_RETRIES=3

# RunwareAI Configuration
RUNWAREAI_API_URL=https://api.runwareai.com
RUNWAREAI_API_TOKEN=your-runwareai-token
RUNWAREAI_TIMEOUT=60
RUNWAREAI_RATE_LIMIT_DELAY=1000

# Additional providers can be added here
```

## Installation and Setup

### Automated Deployment Script

#### Deploy Script (`deploy.sh`)
```bash
#!/bin/bash

set -e  # Exit on any error

echo "🚀 Starting AI StyleGallery deployment..."

# Variables
APP_DIR="/var/www/ai-stylegallery"
BACKUP_DIR="/var/backups/ai-stylegallery"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# Create backup
echo "📦 Creating backup..."
mkdir -p "$BACKUP_DIR"
tar -czf "$BACKUP_DIR/backup_$TIMESTAMP.tar.gz" -C "$(dirname "$APP_DIR")" "$(basename "$APP_DIR")"

# Navigate to app directory
cd "$APP_DIR"

# Backup current .env
cp .env ".env.backup.$TIMESTAMP"

# Pull latest changes
echo "📥 Pulling latest changes..."
git pull origin main

# Install PHP dependencies
echo "📦 Installing PHP dependencies..."
composer install --no-dev --optimize-autoloader

# Install Node.js dependencies
echo "📦 Installing Node.js dependencies..."
npm ci

# Build assets
echo "🔨 Building frontend assets..."
npm run build

# Run database migrations
echo "🗄️ Running database migrations..."
php artisan migrate --force

# Clear caches
echo "🧹 Clearing caches..."
php artisan config:clear
php artisan route:clear
php artisan view:clear
php artisan event:clear

# Optimize application
echo "⚡ Optimizing application..."
php artisan optimize

# Set proper permissions
echo "🔐 Setting permissions..."
chown -R www-data:www-data storage bootstrap/cache
chmod -R 755 storage bootstrap/cache
chmod -R 644 storage/logs/*.log

# Restart web server
echo "🔄 Restarting web server..."
sudo systemctl reload nginx
sudo systemctl restart php8.3-fpm

# Run health check
echo "🏥 Running health check..."
sleep 10
curl -f https://your-domain.com/api/health || exit 1

echo "✅ Deployment completed successfully!"
echo "📋 Backup saved as: $BACKUP_DIR/backup_$TIMESTAMP.tar.gz"
```

### Manual Installation Steps

#### 1. System Preparation
```bash
# Update system packages
sudo apt update && sudo apt upgrade -y

# Install required software
sudo apt install -y nginx php8.3 php8.3-fpm php8.3-cli php8.3-common php8.3-mysql php8.3-sqlite3 php8.3-redis php8.3-curl php8.3-gd php8.3-mbstring php8.3-xml php8.3-zip php8.3-bcmath php8.3-intl

# Install Composer
curl -sS https://getcomposer.org/installer | php
sudo mv composer.phar /usr/local/bin/composer

# Install Node.js and npm
curl -fsSL https://deb.nodesource.com/setup_20.x | sudo -E bash -
sudo apt install -y nodejs

# Install Redis
sudo apt install -y redis-server

# Start and enable Redis
sudo systemctl start redis-server
sudo systemctl enable redis-server
```

#### 2. Application Setup
```bash
# Create application directory
sudo mkdir -p /var/www/ai-stylegallery
sudo chown www-data:www-data /var/www/ai-stylegallery

# Clone repository (or upload files)
git clone https://github.com/your-repo/ai-stylegallery.git /var/www/ai-stylegallery
cd /var/www/ai-stylegallery

# Install PHP dependencies
composer install --no-dev

# Install Node.js dependencies
npm install

# Copy environment file
cp .env.example .env

# Generate application key
php artisan key:generate

# Configure database
touch database/database.sqlite
php artisan migrate

# Build frontend assets
npm run build

# Set permissions
sudo chown -R www-data:www-data storage bootstrap/cache
chmod -R 755 storage bootstrap/cache
```

#### 3. Web Server Configuration

##### Nginx Configuration (`/etc/nginx/sites-available/ai-stylegallery`)
```nginx
server {
    listen 80;
    server_name your-domain.com;
    root /var/www/ai-stylegallery/public;

    # Security headers
    add_header X-Frame-Options "SAMEORIGIN" always;
    add_header X-Content-Type-Options "nosniff" always;
    add_header X-XSS-Protection "1; mode=block" always;
    add_header Referrer-Policy "strict-origin-when-cross-origin" always;

    # Handle static assets
    location / {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # PHP processing
    location ~ \.php$ {
        include snippets/fastcgi-php.conf;
        fastcgi_pass unix:/var/run/php/php8.3-fpm.sock;
        fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
        include fastcgi_params;
        fastcgi_read_timeout 300;
    }

    # Static assets caching
    location ~* \.(js|css|png|jpg|jpeg|gif|ico|svg|woff|woff2|ttf|eot)$ {
        expires 1y;
        add_header Cache-Control "public, immutable";
        try_files $uri @proxy;
    }

    # Deny access to sensitive files
    location ~ /\.ht {
        deny all;
    }

    # API routes (optional, for better handling)
    location /api/ {
        try_files $uri $uri/ /index.php?$query_string;
    }

    # Health check endpoint
    location /health {
        access_log off;
        return 200 "healthy\n";
        add_header Content-Type text/plain;
    }
}

server {
    listen 443 ssl http2;
    server_name your-domain.com;
    # SSL configuration...
    # Same directives as above...
}
```

##### Apache Configuration (Alternative)
```apache
<VirtualHost *:80>
    ServerName your-domain.com
    DocumentRoot /var/www/ai-stylegallery/public

    <Directory /var/www/ai-stylegallery/public>
        Options -Indexes +FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    # Security headers
    Header always set X-Frame-Options "SAMEORIGIN"
    Header always set X-Content-Type-Options "nosniff"
    Header always set X-XSS-Protection "1; mode=block"
    Header always set Referrer-Policy "strict-origin-when-cross-origin"

    # Handle PHP files
    <FilesMatch \.php$>
        SetHandler "proxy:unix:/var/run/php/php8.3-fpm.sock|fcgi://localhost"
    </FilesMatch>

    # Health check
    <Location "/health">
        Require all granted
        Header set Content-Type "text/plain"
        Header set Cache-Control "no-cache, no-store, must-revalidate"
    </Location>

    ErrorLog ${APACHE_LOG_DIR}/ai-stylegallery_error.log
    CustomLog ${APACHE_LOG_DIR}/ai-stylegallery_access.log combined
</VirtualHost>
```

## Operational Procedures

### Database Management

#### Backup Strategy
```bash
# Daily database backup
#!/bin/bash
BACKUP_DIR="/var/backups/ai-stylegallery"
mkdir -p "$BACKUP_DIR"

# SQLite backup (default)
cp /var/www/ai-stylegallery/database/database.sqlite "$BACKUP_DIR/db_$(date +%Y%m%d_%H%M%S).sqlite"

# MySQL backup (if using MySQL)
# mysqldump -h localhost -u username -p password ai_stylegallery > "$BACKUP_DIR/db_$(date +%Y%m%d_%H%M%S).sql"

# Compress and cleanup old backups
find "$BACKUP_DIR" -name "db_*" -type f -mtime +7 -delete
```

#### Migration Management
```bash
# Run migrations
php artisan migrate

# Rollback if needed
php artisan migrate:rollback

# Check migration status
php artisan migrate:status

# Seed database (for initial data)
php artisan db:seed
```

### File Storage Management

#### Storage Structure
```
/var/www/ai-stylegallery/
├── storage/
│   ├── app/
│   │   ├── public/
│   │   │   ├── uploads/           # User uploaded images
│   │   │   └── style_previews/    # AI style preview images
│   │   └── .gitignore
│   ├── framework/
│   │   ├── cache/
│   │   ├── sessions/
│   │   └── views/
│   ├── logs/                      # Application logs
│   └── .gitignore
```

#### Storage Permissions
```bash
# Set proper ownership
sudo chown -R www-data:www-data /var/www/ai-stylegallery/storage

# Set proper permissions
sudo chmod -R 755 /var/www/ai-stylegallery/storage
sudo chmod -R 644 /var/www/ai-stylegallery/storage/logs/*.log

# Create symbolic link (if needed)
php artisan storage:link
```

### Log Management

#### Log Configuration
```php
// config/logging.php
'channels' => [
    'stack' => [
        'driver' => 'stack',
        'channels' => ['single', 'daily'],
    ],
    'single' => [
        'driver' => 'single',
        'path' => storage_path('logs/laravel.log'),
        'level' => env('LOG_LEVEL', 'debug'),
    ],
    'daily' => [
        'driver' => 'daily',
        'path' => storage_path('logs/laravel.log'),
        'level' => env('LOG_LEVEL', 'debug'),
        'days' => 14,
    ],
],
```

#### Log Rotation
```bash
# Logrotate configuration (/etc/logrotate.d/ai-stylegallery)
/var/www/ai-stylegallery/storage/logs/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 644 www-data www-data
    postrotate
        systemctl reload nginx
    endscript
}
```

### Monitoring and Health Checks

#### Health Check Endpoint
```php
// routes/web.php
Route::get('/health', function () {
    try {
        // Database check
        DB::connection()->getPdo();

        // Storage check
        Storage::disk('public')->exists('test');

        // Cache check
        Cache::store('redis')->put('health', 'ok', 10);

        return response()->json([
            'status' => 'healthy',
            'timestamp' => now()->toISOString(),
            'version' => config('app.version'),
        ]);
    } catch (Exception $e) {
        return response()->json([
            'status' => 'unhealthy',
            'error' => $e->getMessage(),
            'timestamp' => now()->toISOString(),
        ], 503);
    }
});
```

#### Monitoring Setup
```bash
# Install monitoring tools
sudo apt install -y htop iotop nethogs

# Set up log monitoring
sudo apt install -y logwatch

# Configure process monitoring
sudo apt install -y monit

# Monit configuration for AI StyleGallery
# /etc/monit/conf.d/ai-stylegallery
check process php-fpm with pidfile /var/run/php/php8.3-fpm.pid
    start program = "/etc/init.d/php8.3-fpm start"
    stop program = "/etc/init.d/php8.3-fpm stop"
    if cpu > 60% for 2 cycles then alert
    if memory usage > 80% for 5 cycles then alert

check process nginx with pidfile /var/run/nginx.pid
    start program = "/etc/init.d/nginx start"
    stop program = "/etc/init.d/nginx stop"
    if cpu > 60% for 2 cycles then alert
    if memory usage > 80% for 5 cycles then alert
```

## Security Hardening

### Firewall Configuration
```bash
# UFW (Uncomplicated Firewall)
sudo ufw allow 'OpenSSH'
sudo ufw allow 'Nginx Full'
sudo ufw --force enable

# Advanced firewall rules
sudo ufw allow from your-admin-ip to any port 22
sudo ufw allow from your-office-ip-range to any port 80
sudo ufw allow from your-office-ip-range to any port 443
```

### SSL/TLS Setup
```bash
# Install Certbot for Let's Encrypt
sudo apt install -y certbot python3-certbot-nginx

# Generate SSL certificate
sudo certbot --nginx -d your-domain.com -d www.your-domain.com

# Auto-renewal (add to crontab)
sudo crontab -e
# Add: 0 12 * * * /usr/bin/certbot renew --quiet
```

### Security Updates
```bash
# Automated security updates
sudo apt install -y unattended-upgrades
sudo dpkg-reconfigure -plow unattended-upgrades

# Manual security updates
sudo apt update && sudo apt upgrade -y
sudo apt autoremove -y
sudo apt autoclean
```

## Performance Optimization

### PHP-FPM Optimization
```ini
# /etc/php/8.3/fpm/pool.d/www.conf
pm = dynamic
pm.max_children = 50
pm.start_servers = 5
pm.min_spare_servers = 5
pm.max_spare_servers = 35
pm.max_requests = 500

# Process manager settings
pm.process_idle_timeout = 10s
pm.max_requests = 1000

# Memory optimization
php_admin_value[memory_limit] = 256M
php_admin_flag[opcache.enable] = 1
```

### MySQL Optimization (if using MySQL)
```ini
# /etc/mysql/mysql.conf.d/mysqld.cnf
[mysqld]
innodb_buffer_pool_size = 1G
innodb_log_file_size = 256M
innodb_flush_log_at_trx_commit = 2
query_cache_size = 0
query_cache_type = 0
innodb_flush_method = O_DIRECT

# Connection settings
max_connections = 100
wait_timeout = 28800
interactive_timeout = 28800
```

### Nginx Optimization
```nginx
# Performance optimizations
worker_processes auto;
worker_rlimit_nofile 1024;

events {
    worker_connections 1024;
    use epoll;
    multi_accept on;
}

http {
    # Caching
    proxy_cache_path /tmp/nginx_cache levels=1:2 keys_zone=my_cache:10m max_size=1g inactive=60m use_temp_path=off;

    # Gzip compression
    gzip on;
    gzip_vary on;
    gzip_min_length 1024;
    gzip_proxied expired no-cache no-store private must-revalidate auth;
    gzip_types text/plain text/css text/xml text/javascript application/javascript application/xml+rss application/json;

    # Rate limiting
    limit_req_zone $binary_remote_addr zone=api:10m rate=10r/s;
    limit_req_zone $binary_remote_addr zone=upload:10m rate=2r/s;
}
```

## Troubleshooting

### Common Issues

#### Application Not Loading
```bash
# Check PHP-FPM status
sudo systemctl status php8.3-fpm

# Check Nginx status
sudo systemctl status nginx

# Check application logs
tail -f /var/www/ai-stylegallery/storage/logs/laravel.log

# Test PHP processing
php -f /var/www/ai-stylegallery/public/index.php
```

#### Database Connection Issues
```bash
# Test database connection
php artisan tinker --execute="DB::connection()->getPdo(); echo 'Database connected';"

# Check database file permissions (SQLite)
ls -la /var/www/ai-stylegallery/database/database.sqlite

# Check database configuration
php artisan config:cache
php artisan config:clear
```

#### File Upload Issues
```bash
# Check storage permissions
ls -la /var/www/ai-stylegallery/storage/app/public/

# Check PHP upload settings
php -i | grep upload

# Test file upload
php -r "move_uploaded_file('/tmp/test.txt', '/var/www/ai-stylegallery/storage/app/public/uploads/test.txt');"
```

#### AI Service Connection Issues
```bash
# Test ComfyUI connection
curl -X GET "https://your-comfyui-server.com/queue"

# Test RunwareAI connection
curl -X POST "https://api.runwareai.com" \
  -H "Authorization: Bearer your-token" \
  -H "Content-Type: application/json" \
  -d '{"taskType": "authentication", "apiKey": "your-token"}'

# Check API provider configuration
php artisan tinker --execute="App\Models\ApiProvider::all()"
```

### Debug Mode

#### Enable Debug Mode (Development Only)
```bash
# Edit .env file
APP_DEBUG=true
LOG_LEVEL=debug

# Clear config cache
php artisan config:clear

# Check detailed error logs
tail -f /var/www/ai-stylegallery/storage/logs/laravel.log
```

#### Performance Profiling
```bash
# Enable query logging
php artisan tinker --execute="DB::enableQueryLog();"

# Profile application performance
php artisan tinker --execute="dump(app()->getLoadedProviders());"

# Memory usage
php -r "echo 'Memory usage: ' . memory_get_peak_usage(true) / 1024 / 1024 . 'MB';"
```

## Backup and Recovery

### Complete System Backup
```bash
#!/bin/bash
# Full system backup script

BACKUP_DIR="/var/backups/ai-stylegallery"
APP_DIR="/var/www/ai-stylegallery"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

# Create backup directory
mkdir -p "$BACKUP_DIR"

# Backup application files
tar -czf "$BACKUP_DIR/app_$TIMESTAMP.tar.gz" -C "$(dirname "$APP_DIR")" "$(basename "$APP_DIR")"

# Backup database
cp "$APP_DIR/database/database.sqlite" "$BACKUP_DIR/db_$TIMESTAMP.sqlite"

# Backup Nginx configuration
cp /etc/nginx/sites-available/ai-stylegallery "$BACKUP_DIR/nginx_config_$TIMESTAMP"

# Backup SSL certificates
cp -r /etc/letsencrypt/live/your-domain.com "$BACKUP_DIR/ssl_$TIMESTAMP"

# Cleanup old backups (keep 7 days)
find "$BACKUP_DIR" -type f -mtime +7 -delete

echo "Backup completed: $BACKUP_DIR/backup_$TIMESTAMP"
```

### Recovery Procedure
```bash
#!/bin/bash
# Recovery script

BACKUP_DIR="/var/backups/ai-stylegallery"
APP_DIR="/var/www/ai-stylegallery"

# Stop services
sudo systemctl stop nginx php8.3-fpm

# Restore application files
LATEST_BACKUP=$(ls -t "$BACKUP_DIR/app_"*.tar.gz | head -1)
sudo tar -xzf "$LATEST_BACKUP" -C "$(dirname "$APP_DIR")"

# Restore database
LATEST_DB=$(ls -t "$BACKUP_DIR/db_"*.sqlite | head -1)
cp "$LATEST_DB" "$APP_DIR/database/database.sqlite"

# Restore Nginx configuration
LATEST_NGINX=$(ls -t "$BACKUP_DIR/nginx_config_"* | head -1)
sudo cp "$LATEST_NGINX" /etc/nginx/sites-available/ai-stylegallery

# Set permissions
sudo chown -R www-data:www-data "$APP_DIR"
sudo chmod -R 755 "$APP_DIR/storage" "$APP_DIR/bootstrap/cache"

# Start services
sudo systemctl start php8.3-fpm nginx

# Test recovery
curl -f https://your-domain.com/health || exit 1

echo "Recovery completed successfully!"
```

## Scaling Considerations

### Horizontal Scaling

#### Load Balancer Setup
```nginx
# Load balancer configuration
upstream ai-stylegallery_backend {
    server 192.168.1.10:80;
    server 192.168.1.11:80;
    server 192.168.1.12:80;

    # Health checks
    keepalive 32;
}

server {
    listen 80;
    server_name your-domain.com;

    location / {
        proxy_pass http://ai-stylegallery_backend;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        proxy_set_header X-Forwarded-Proto $scheme;

        # Health check
        proxy_next_upstream error timeout invalid_header http_500 http_502 http_503 http_504;
    }
}
```

#### Shared Storage
```bash
# NFS shared storage for uploads
sudo apt install -y nfs-kernel-server
sudo mkdir -p /var/nfs/ai-stylegallery
sudo chown www-data:www-data /var/nfs/ai-stylegallery

# Mount on web servers
sudo mount -t nfs storage-server:/var/nfs/ai-stylegallery /var/www/ai-stylegallery/storage/app/public
```

### Database Scaling

#### Read Replicas
```bash
# MySQL read replica setup
CHANGE MASTER TO
  MASTER_HOST='master-db-server',
  MASTER_USER='replica_user',
  MASTER_PASSWORD='replica_password',
  MASTER_LOG_FILE='mysql-bin.000001',
  MASTER_LOG_POS=107;
```

#### Redis Cluster
```bash
# Redis cluster setup for horizontal scaling
redis-cli --cluster create \
  192.168.1.10:6379 \
  192.168.1.11:6379 \
  192.168.1.12:6379 \
  --cluster-replicas 0
```

## Maintenance Procedures

### Regular Maintenance Tasks

#### Daily Tasks
- Monitor system resources (CPU, memory, disk)
- Check application logs for errors
- Verify AI service connectivity
- Test backup restoration

#### Weekly Tasks
- Review and rotate application logs
- Check for security updates
- Monitor storage usage and cleanup
- Test full application functionality

#### Monthly Tasks
- Full system backup and verification
- Security audit and penetration testing
- Performance analysis and optimization
- Dependency updates and testing

### Emergency Procedures

#### Service Outage Response
```bash
# Quick health check
curl -f https://your-domain.com/health

# Check service status
sudo systemctl status nginx php8.3-fpm

# View recent logs
sudo tail -f /var/log/nginx/error.log
sudo tail -f /var/www/ai-stylegallery/storage/logs/laravel.log

# Restart services if needed
sudo systemctl restart nginx php8.3-fpm
```

#### Data Recovery
```bash
# From backup
cd /var/backups/ai-stylegallery
LATEST_BACKUP=$(ls -t *.tar.gz | head -1)
sudo tar -xzf "$LATEST_BACKUP" -C /var/www/ai-stylegallery --strip-components=1

# Restore database
LATEST_DB=$(ls -t db_*.sqlite | head -1)
cp "$LATEST_DB" /var/www/ai-stylegallery/database/database.sqlite
```

## Support and Documentation

### Documentation Locations
- **API Documentation**: `/prp/api-specification.md`
- **Component Documentation**: `/prp/frontend-components.md`
- **Deployment Guide**: This document
- **User Manual**: Application help system

### Support Contacts
- **Technical Support**: dev-team@your-domain.com
- **System Administrator**: admin@your-domain.com
- **Security Issues**: security@your-domain.com

### Training Materials
- **Admin Training**: Filament admin panel usage
- **Developer Guide**: Contributing to the codebase
- **Operations Manual**: Day-to-day system management

## Compliance and Legal

### Data Protection
- **GDPR Compliance**: User data handling procedures
- **Data Retention**: Configurable data retention policies
- **Privacy Policy**: User data collection and usage transparency

### Security Compliance
- **SSL/TLS**: HTTPS encryption for all communications
- **Data Encryption**: Sensitive data encryption at rest
- **Access Logging**: Comprehensive audit trails

### Licensing
- **Application License**: Open source or commercial license
- **Third-party Libraries**: Compliance with library licenses
- **AI Service Terms**: Compliance with AI provider terms of service

## Future Deployment Enhancements

### Containerization (Docker)

#### Dockerfile
```dockerfile
FROM php:8.3-fpm

# Install system dependencies
RUN apt-get update && apt-get install -y \
    git curl libpng-dev libonig-dev libxml2-dev libzip-dev zip unzip \
    && docker-php-ext-install pdo_mysql mbstring exif pcntl bcmath gd zip

# Install Composer
COPY --from=composer:latest /usr/bin/composer /usr/bin/composer

# Copy application code
WORKDIR /var/www/ai-stylegallery
COPY . .

# Install dependencies
RUN composer install --no-dev --optimize-autoloader

# Set permissions
RUN chown -R www-data:www-data storage bootstrap/cache
```

#### Docker Compose
```yaml
version: '3.8'
services:
  web:
    build: .
    ports:
      - "80:80"
    volumes:
      - ./storage/app/public:/var/www/ai-stylegallery/storage/app/public
    depends_on:
      - redis
      - db

  redis:
    image: redis:7-alpine

  db:
    image: postgres:15-alpine
    environment:
      POSTGRES_DB: ai_stylegallery
      POSTGRES_USER: laravel
      POSTGRES_PASSWORD: password
```

### CI/CD Pipeline

#### GitHub Actions Workflow
```yaml
name: Deploy to Production
on:
  push:
    branches: [ main ]

jobs:
  deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v3

      - name: Setup PHP
        uses: shivammathur/setup-php@v2
        with:
          php-version: '8.3'

      - name: Install Dependencies
        run: composer install --no-dev

      - name: Run Tests
        run: php artisan test

      - name: Deploy to Server
        uses: appleboy/ssh-action@master
        with:
          host: ${{ secrets.SERVER_HOST }}
          username: ${{ secrets.SERVER_USER }}
          key: ${{ secrets.SERVER_SSH_KEY }}
          script: |
            cd /var/www/ai-stylegallery
            ./deploy.sh
```

### Monitoring and Alerting

#### Prometheus Metrics
```php
// Prometheus metrics endpoint
Route::get('/metrics', function () {
    $metrics = [
        'app_requests_total' => \DB::table('access_logs')->count(),
        'app_users_total' => \App\Models\User::count(),
        'app_images_total' => \App\Models\Image::count(),
        'app_processing_time' => \Cache::get('avg_processing_time', 0),
    ];

    return response(implode("\n", array_map(
        fn($key, $value) => "{$key} {$value}",
        array_keys($metrics),
        array_values($metrics)
    )), 200, ['Content-Type' => 'text/plain']);
});
```

#### Grafana Dashboard
- Application performance metrics
- AI service response times
- User activity and engagement
- System resource utilization
- Error rates and alerting

This comprehensive deployment guide provides all necessary information for successfully deploying and maintaining the AI StyleGallery application in production environments.