<?php
declare(strict_types=1);

if (PHP_SAPI !== 'cli') {
    http_response_code(404);
    exit;
}

require_once dirname(__DIR__) . DIRECTORY_SEPARATOR . 'app' . DIRECTORY_SEPARATOR . 'bootstrap.php';
app_bootstrap();

$cliTimezone = (string) (app_config('site')['timezone'] ?? 'UTC');
date_default_timezone_set(in_array($cliTimezone, DateTimeZone::listIdentifiers(), true) ? $cliTimezone : 'UTC');

use App\Database\Connection;
use App\System\DiagnosticService;

$requireReleaseManifest = in_array('--require-release-manifest', $argv, true)
    || strtolower(trim((string) app_env('APP_ENV', ''))) === 'production';
$strictReleaseFiles = in_array('--strict-release-files', $argv, true);

$pdo = null;
if (extension_loaded('pdo_mysql')) {
    try {
        $pdo = Connection::connect(app_config('database'));
    } catch (Throwable $throwable) {
        fwrite(STDERR, 'Database connection failed: ' . $throwable->getMessage() . PHP_EOL);
    }
}

$result = (new DiagnosticService($pdo, $_SERVER))
    ->inspect(true, $requireReleaseManifest, $strictReleaseFiles);

/** CLI labels for the shared check ids; the admin panel translates the same ids. */
$labels = [
    'version' => 'Quaeriva version',
    'root' => 'Project root',
    'php' => 'PHP',
    'pdo_mysql' => 'PDO MySQL',
    'json' => 'JSON extension',
    'mbstring' => 'mbstring',
    'curl' => 'cURL',
    'openssl' => 'OpenSSL',
    'server_software' => 'Server',
    'build_id' => 'Release build',
    'built_at' => 'Build time',
    'release_manifest' => 'Release manifest',
    'base_path' => 'Base path',
    'base_source' => 'Base path source',
    'base_candidates' => 'Base path candidates',
    'base_ambiguous' => 'Base path ambiguous',
    'admin_path' => 'Admin path',
    'https' => 'HTTPS',
    'app_env' => 'APP_ENV',
    'log_path' => 'Log path',
    'log_writable' => 'Log writable',
    'session_handler' => 'Session handler',
    'session_path' => 'Session path',
    'file_permissions' => 'File permissions',
    'database_config_source' => 'Database config source',
    'database' => 'Database',
    'database_version' => 'Database server',
    'migrations_applied' => 'Applied migrations',
    'migrations_pending' => 'Pending migrations',
    'schema_integrity' => 'Schema integrity',
    'layout' => 'Layout / sections / widgets',
];

$marks = [
    DiagnosticService::PASS => 'OK  ',
    DiagnosticService::WARN => 'WARN',
    DiagnosticService::FAIL => 'FAIL',
    DiagnosticService::INFO => '    ',
];

foreach ($result['checks'] as $check) {
    $label = $labels[$check['id']] ?? $check['id'];
    fwrite(STDOUT, $marks[$check['state']] . ' ' . str_pad($label . ':', 26) . $check['value'] . PHP_EOL);
    foreach ($check['detail'] as $detail) {
        fwrite(STDOUT, str_repeat(' ', 5) . '  - ' . $detail . PHP_EOL);
    }
}

$layout = DiagnosticService::find($result, 'layout');
if ($layout !== null && $layout['state'] === DiagnosticService::FAIL) {
    fwrite(STDOUT, 'Layout remediation:       Run database upgrade from the administration banner or execute "php bin/migrate.php".' . PHP_EOL);
}

if ($pdo === null && !extension_loaded('pdo_mysql')) {
    fwrite(STDOUT, 'Database checks skipped because pdo_mysql is not loaded.' . PHP_EOL);
    exit(2);
}

exit($result['healthy'] ? 0 : 3);
