<?php

declare(strict_types=1);
$root = dirname(__DIR__);
if (PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit();
}
foreach (
    [
        'DB',
        'Migrations',
        'I18n',
        'AppSettings',
        'Auth',
        'AuditService',
        'BackupService',
        'NotificationService',
        'PrivacyService',
    ]
    as $class
) {
    require_once $root . '/app/Services/' . $class . '.php';
}
Migrations::run($root . '/migrations');
I18n::setLocale(AppSettings::get('app_language'));
$command = $argv[1] ?? 'run';
try {
    $results = [];
    if (in_array($command, ['run', 'backup'], true)) {
        $results['backup'] = BackupService::runScheduled($command === 'backup' && in_array('--force', $argv, true));
    }
    if (in_array($command, ['run', 'privacy'], true)) {
        $results['privacy'] = PrivacyService::maintenance();
    }
    if (in_array($command, ['run', 'notifications'], true)) {
        $results['notifications'] = NotificationService::send(false);
    }
    echo json_encode(
    ['ok' => true, 'at' => date(DATE_ATOM), 'results' => $results],
    JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE,
),
        PHP_EOL;
} catch (Throwable $e) {
    fwrite(STDERR, json_encode(['ok' => false, 'error' => $e->getMessage()], JSON_UNESCAPED_UNICODE) . PHP_EOL);
    exit(1);
}
