#!/usr/bin/env php
<?php

declare(strict_types=1);

require_once __DIR__ . '/../src/database.php';

use Notifier\Database;

$options = getopt('', ['max-minutes::', 'email::', 'from::', 'subject-prefix::', 'method::']);

$configPath = __DIR__ . '/../config.php';
if (!file_exists($configPath)) {
    fwrite(STDERR, "Error: config.php not found\n");
    exit(1);
}
$config = require $configPath;

$healthConfig = $config['cron_health'] ?? [];

$maxMinutes = (int) ($options['max-minutes'] ?? ($healthConfig['max_age_minutes'] ?? 10));
$emailTo = (string) ($options['email'] ?? ($healthConfig['email_to'] ?? ''));
$from = (string) ($options['from'] ?? ($healthConfig['from'] ?? ('notifier@' . gethostname())));
$subjectPrefix = (string) ($options['subject-prefix'] ?? ($healthConfig['subject_prefix'] ?? '[Notifier]'));
$method = (string) ($options['method'] ?? ($healthConfig['method'] ?? 'mail'));

if ($maxMinutes <= 0) {
    $maxMinutes = 10;
}

if ($emailTo === '') {
    fwrite(STDERR, "Error: email recipient not configured\n");
    exit(1);
}

try {
    $db = new Database($config['database']['path'] ?? __DIR__ . '/../database.sqlite');
    $pdo = $db->getPdo();
} catch (Exception $e) {
    fwrite(STDERR, "Database error: " . $e->getMessage() . "\n");
    exit(1);
}

$tableExists = $pdo->query("SELECT name FROM sqlite_master WHERE type='table' AND name='scheduler_state'")->fetchColumn();
if (!$tableExists) {
    fwrite(STDERR, "Error: scheduler_state table missing. Run php scripts/migrate.php.\n");
    exit(1);
}

$row = $pdo->query('SELECT * FROM scheduler_state WHERE id = 1')->fetch(PDO::FETCH_ASSOC);
if (!$row) {
    fwrite(STDERR, "Error: scheduler_state row missing. Run php scripts/migrate.php.\n");
    exit(1);
}

$utc = new DateTimeZone('UTC');
$now = new DateTime('now', $utc);

$lastRunAt = new DateTime($row['last_run_at'], $utc);
$lastSuccessAt = !empty($row['last_success_at']) ? new DateTime($row['last_success_at'], $utc) : null;
$lastAlertAt = !empty($row['last_alert_at']) ? new DateTime($row['last_alert_at'], $utc) : null;

$ageSeconds = $now->getTimestamp() - $lastRunAt->getTimestamp();
$ageMinutes = (int) floor($ageSeconds / 60);
$stale = $ageMinutes > $maxMinutes;

$lastError = trim((string) ($row['last_error'] ?? ''));
$hasError = $lastError !== '';

$shouldAlert = $stale || $hasError;
if (!$shouldAlert) {
    exit(0);
}

if ($lastAlertAt && $lastAlertAt >= $lastRunAt) {
    exit(0);
}

$detailsLines = [];
$detailsLines[] = "Status: " . ($stale ? 'STALE' : 'ERROR');
$detailsLines[] = "Last run (UTC): " . $lastRunAt->format('Y-m-d H:i:s');
$detailsLines[] = "Age (minutes): " . $ageMinutes;
$detailsLines[] = "Last success (UTC): " . ($lastSuccessAt ? $lastSuccessAt->format('Y-m-d H:i:s') : 'never');
if ($hasError) {
    $detailsLines[] = "Last error: " . $lastError;
}
$details = implode("\n", $detailsLines);

$subject = trim($subjectPrefix . ' Notifier alert: scheduler issue detected');
$prompt = "Please investigate the Notifier cron scheduler health alert. Check whether cron is running, confirm scheduler.php is executing every minute, review logs/scheduler.log and logs/cron-health.log, and inspect the scheduler_state table for stale last_run_at or last_error. Identify the root cause, explain it, and implement a fix.\n\nVerify with a test run and confirm the heartbeat updates.";

$textBody = "Notifier detected a cron-job scheduler issue. The details are the following:\n"
    . $details
    . "\n\nNext step (recommended):\n"
    . "Go to your server and tell the AI agent:\n\n"
    . $prompt
    . "\n";

$htmlBody = "<p>Notifier detected a cron-job scheduler issue. The details are the following:</p>"
    . "<pre style=\"background:#f6f6f6;padding:12px;border-radius:6px;\">"
    . htmlspecialchars($details, ENT_QUOTES, 'UTF-8')
    . "</pre>"
    . "<p><strong>Next step (recommended):</strong><br>Go to your server and tell the AI agent:</p>"
    . "<blockquote style=\"border-left:3px solid #ccc;margin:0;padding-left:12px;white-space:pre-wrap;\">"
    . htmlspecialchars($prompt, ENT_QUOTES, 'UTF-8')
    . "</blockquote>";

$sent = false;
$errorMessage = null;

if ($method === 'mailersend') {
    $mailerConfig = $config['mailer_send'] ?? [];
    $apiKey = $mailerConfig['api_key'] ?? '';
    $fromEmail = $mailerConfig['from_email'] ?? '';
    $fromName = $mailerConfig['from_name'] ?? 'Notifier';

    if ($apiKey === '' || $fromEmail === '') {
        fwrite(STDERR, "Error: mailersend api_key/from_email not configured\n");
        exit(1);
    }

    $payload = [
        'from' => [
            'email' => $fromEmail,
            'name' => $fromName,
        ],
        'to' => [
            [
                'email' => $emailTo,
                'name' => 'Recipient',
            ],
        ],
        'subject' => $subject,
        'text' => $textBody,
        'html' => $htmlBody,
    ];

    $ch = curl_init('https://api.mailersend.com/v1/email');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'Authorization: Bearer ' . $apiKey,
        'Content-Type: application/json',
    ]);
    curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
    $response = curl_exec($ch);
    $httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $curlError = curl_error($ch);
    curl_close($ch);

    if ($response === false) {
        $errorMessage = "MailerSend cURL error: {$curlError}";
    } elseif ($httpCode !== 202) {
        $errorMessage = "MailerSend error (HTTP {$httpCode}): " . ($response ?: 'Empty response');
    } else {
        $sent = true;
    }
} else {
    $headers = "From: {$from}\r\n";
    $sent = mail($emailTo, $subject, $textBody, $headers);
    if (!$sent) {
        $errorMessage = 'Failed to send email via mail()';
    }
}

if (!$sent) {
    fwrite(STDERR, "Error: {$errorMessage}\n");
    exit(1);
}

$stmt = $pdo->prepare('UPDATE scheduler_state SET last_alert_at = datetime(\'now\'), updated_at = datetime(\'now\') WHERE id = 1');
$stmt->execute();

exit(0);
