<?php
require_once __DIR__.'/../config/config.php';
require_once __DIR__.'/../config/database.php';
require_once __DIR__.'/../includes/functions.php';

try {
    if (!function_exists('afStage25Metrics')) {
        echo "Etapa 25 não carregada.\n";
        exit(1);
    }
    afStage25ExpireOldReleases($pdo);

    $autoRevoke = (bool)afStage25Config($pdo, 'stage25_auto_revoke_on_critical_alert', true);
    $critical = afStage25TableExists($pdo, 'af_security_alerts')
        ? afStage25Count($pdo, "SELECT COUNT(*) FROM af_security_alerts WHERE severity='critical' AND status IN ('open','triage','in_review')")
        : 0;
    if ($autoRevoke && $critical > 0 && afStage25ActiveRelease($pdo)) {
        afStage25RevokeRelease($pdo, 0, 'Revogação automática: alerta crítico aberto na Etapa 24.');
    }

    $last = afStage25Config($pdo, 'stage25_cron_last_run_at', '');
    $shouldRunChecklist = true;
    if ($last !== '') {
        $ts = strtotime((string)$last);
        $shouldRunChecklist = !$ts || $ts < strtotime('-24 hours');
    }
    if ($shouldRunChecklist && afStage25TableExists($pdo, 'af_stage25_test_runs')) {
        afStage25RunAutomatedChecklist($pdo, 0, 'cron', afStage25CurrentMode($pdo));
    }
    afStage25SetConfig($pdo, 'stage25_cron_last_run_at', date('Y-m-d H:i:s'), 'string', 'Última execução da rotina cron da Etapa 25.');
    echo "Etapa 25 OK em ".date('Y-m-d H:i:s')."\n";
} catch (Throwable $e) {
    error_log('[AURA-STAGE25-CRON] '.$e->getMessage());
    echo "Erro Etapa 25: ".$e->getMessage()."\n";
    exit(1);
}
