#!/usr/bin/env php
<?php
/**
 * AI Monitor Maintenance
 * Runs daily via cron. Handles data retention cleanup:
 * - Auto-resolves issues with no recurrence for 7 days
 * - Purges old resolved issues (90 days)
 * - Purges old completed/failed log reviews (30 days)
 * - Purges old sent/failed emails (30 days)
 */

echo date('Y-m-d H:i:s') . " Starting AI monitor maintenance\n";

try {
    // Connect to database (use same extraction method as config.php)
    $password = trim(shell_exec('cat /root/.my.cnf | grep password | cut -f2- -d='));
    $db = new PDO('mysql:host=127.0.0.1;dbname=whp;charset=utf8mb4', 'root', $password);
    $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

    // 1. Stamp auto_resolved_at on issues with no recurrence for 7 days.
    //    Leaves status='open' so user still reviews; fixed/ignored is a manual action.
    $autoResolved = $db->exec("
        UPDATE whp.ai_monitor_issues
        SET auto_resolved_at = NOW()
        WHERE status = 'open'
          AND auto_resolved_at IS NULL
          AND last_seen < DATE_SUB(NOW(), INTERVAL 7 DAY)
    ");
    echo date('Y-m-d H:i:s') . " Stamped auto_resolved_at on stale open issues: {$autoResolved}\n";

    // 2. Purge fixed/ignored issues older than 90 days.
    $purgedIssues = $db->exec("
        DELETE FROM whp.ai_monitor_issues
        WHERE status IN ('fixed', 'ignored')
          AND status_changed_at < DATE_SUB(NOW(), INTERVAL 90 DAY)
    ");
    echo date('Y-m-d H:i:s') . " Purged fixed/ignored issues (>90 days): {$purgedIssues}\n";

    // 3. Purge completed/failed log reviews older than 30 days.
    $purgedReviews = $db->exec("
        DELETE FROM whp.ai_monitor_log_reviews
        WHERE status IN ('completed', 'failed')
          AND completed_at < DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    echo date('Y-m-d H:i:s') . " Purged old log reviews (>30 days): {$purgedReviews}\n";

    // 4. Purge sent/failed emails older than 30 days
    $purgedEmails = $db->exec("
        DELETE FROM whp.ai_monitor_email_queue
        WHERE status IN ('sent', 'failed')
          AND created_at < DATE_SUB(NOW(), INTERVAL 30 DAY)
    ");
    echo date('Y-m-d H:i:s') . " Purged old emails (>30 days): {$purgedEmails}\n";

    echo date('Y-m-d H:i:s') . " Maintenance complete\n";

} catch (Exception $e) {
    echo date('Y-m-d H:i:s') . " ERROR: " . $e->getMessage() . "\n";
    exit(1);
}
