#!/bin/bash

echo "==========================================="
echo "  Aplicar Correção do Backup Automático"
echo "==========================================="
echo ""

cd /var/www/gestorstream/backend

# Backup do arquivo original
echo "1. Fazendo backup do Kernel.php..."
cp app/Console/Kernel.php app/Console/Kernel.php.backup.$(date +%Y%m%d_%H%M%S)
echo "   ✅ Backup criado"
echo ""

# Verificar se já está corrigido
if grep -q "CORREÇÃO: Carregar helper se necessário" app/Console/Kernel.php; then
    echo "✅ Correção JÁ está aplicada!"
    echo ""
else
    echo "2. Aplicando correção no Kernel.php..."
    
    # Criar arquivo temporário com a correção
    cat > /tmp/kernel_fix.php << 'EOFPHP'
        // Auto database backup - schedule based on frequency setting
        // Use dynamic scheduling based on user configuration
        // We need to check settings dynamically, so we use a closure that runs every minute
        // but only executes when conditions are met
        $schedule->call(function () {
            $enabled = \App\Models\SystemSetting::get('auto_backup_enabled', false);
            if (!$enabled) {
                return;
            }
            
            $frequency = \App\Models\SystemSetting::get('auto_backup_frequency', 'daily');
            $backupTime = \App\Models\SystemSetting::get('auto_backup_time', '02:00');
            
            // CORREÇÃO: Carregar helper se necessário, ou usar fallback
            if (!function_exists('system_timezone')) {
                $helperPath = app_path('Helpers/SystemHelper.php');
                if (file_exists($helperPath)) {
                    require_once $helperPath;
                }
            }
            
            $timezone = function_exists('system_timezone') 
                ? system_timezone() 
                : (\App\Models\SystemSetting::get('system_timezone') ?: config('app.timezone', 'America/Sao_Paulo'));
            
            // Parse time
            [$hour, $minute] = explode(':', $backupTime);
            $now = now($timezone);
            
            // CORREÇÃO: Usar apenas hora e minuto (ignorar segundos)
            // Isso garante que o backup rode mesmo que o scheduler não execute exatamente no segundo 00
            $currentHour = (int) $now->format('H');
            $currentMinute = (int) $now->format('i');
            $scheduledHour = (int) $hour;
            $scheduledMinute = (int) $minute;
            
            // Check if we should run based on frequency
            $shouldRun = false;
            $isScheduledTime = ($currentHour === $scheduledHour && $currentMinute === $scheduledMinute);
            
            switch ($frequency) {
                case 'daily':
                    // Run daily at the specified time
                    $shouldRun = $isScheduledTime;
                    break;
                case 'weekly':
                    // Run on Monday at scheduled time
                    $shouldRun = $now->isMonday() && $isScheduledTime;
                    break;
                case 'monthly':
                    // Run on the 1st of the month at scheduled time
                    $shouldRun = $now->day === 1 && $isScheduledTime;
                    break;
            }
            
            if ($shouldRun) {
                \Illuminate\Support\Facades\Log::info('AutoDatabaseBackup: Executando backup automático agendado', [
                    'frequency' => $frequency,
                    'scheduled_time' => $backupTime,
                    'current_time' => $now->format('H:i:s'),
                    'timezone' => $timezone,
                    'day_of_week' => $now->format('l'),
                    'day_of_month' => $now->day,
                ]);
                \Illuminate\Support\Facades\Artisan::call('database:auto-backup');
            }
        })
            ->everyMinute()
            ->withoutOverlapping()
            ->name('auto-database-backup')
            ->skip(function () {
                // Skip if auto backup is disabled (early exit for performance)
                return !\App\Models\SystemSetting::get('auto_backup_enabled', false);
            });
EOFPHP

    # Usar Python para fazer a substituição (mais confiável que sed)
    python3 << 'EOFPYTHON'
import re

# Ler arquivo
with open('app/Console/Kernel.php', 'r') as f:
    content = f.read()

# Ler correção
with open('/tmp/kernel_fix.php', 'r') as f:
    fix = f.read()

# Padrão para encontrar o bloco antigo
pattern = r"// Auto database backup - schedule based on frequency setting.*?->skip\(function \(\) \{[^}]+\}\);"

# Substituir
new_content = re.sub(pattern, fix.strip(), content, flags=re.DOTALL)

# Salvar
with open('app/Console/Kernel.php', 'w') as f:
    f.write(new_content)

print("   ✅ Correção aplicada com Python")
EOFPYTHON

    if [ $? -ne 0 ]; then
        echo "   ❌ Python falhou, tentando com sed..."
        # Fallback não recomendado
        echo "   ⚠️  Aplicar manualmente seguindo instruções no final"
    fi
fi

echo ""
echo "3. Limpando caches..."
php artisan config:clear > /dev/null 2>&1
php artisan cache:clear > /dev/null 2>&1
php artisan optimize:clear > /dev/null 2>&1
echo "   ✅ Caches limpos"

echo ""
echo "4. Reiniciando PHP-FPM..."
systemctl restart php8.2-fpm
echo "   ✅ PHP-FPM reiniciado"

echo ""
echo "5. Verificando se a correção foi aplicada..."
if grep -q "CORREÇÃO: Carregar helper se necessário" app/Console/Kernel.php; then
    echo "   ✅ Correção APLICADA com sucesso!"
else
    echo "   ❌ Correção NÃO foi aplicada"
    echo ""
    echo "APLICAR MANUALMENTE:"
    echo "  1. nano app/Console/Kernel.php"
    echo "  2. Procurar por: // Auto database backup"
    echo "  3. Substituir todo o bloco até ->skip(...)"
    echo "  4. Ver arquivo: app/Console/Kernel.php.backup.* para referência"
fi

echo ""
echo "6. Verificando schedule:list..."
echo ""
php artisan schedule:list

echo ""
echo "==========================================="
echo "  FIM"
echo "==========================================="
