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

declare(strict_types=1);

require_once dirname(__DIR__).'/config/bootstrap.php';

$errors = [];

if (PHP_VERSION_ID < 80200) {
    $errors[] = sprintf('PHP 8.2 or newer is required; current version is %s.', PHP_VERSION);
}

foreach (['ctype', 'iconv', 'PDO', 'pdo_mysql'] as $extension) {
    if (!extension_loaded($extension)) {
        $errors[] = sprintf('Required PHP extension is missing: %s.', $extension);
    }
}

$requiredVariables = [
    'APP_ENV',
    'APP_DEBUG',
    'APP_SECRET',
    'DATABASE_URL',
    'LOCK_DSN',
    'MAILER_DSN',
    'CONTACT_RECIPIENT',
    'CONTACT_FROM',
    'TURNSTILE_SITE_KEY',
    'TURNSTILE_SECRET_KEY',
];

foreach ($requiredVariables as $name) {
    $value = $_SERVER[$name] ?? $_ENV[$name] ?? null;
    if (!is_string($value) || '' === trim($value)) {
        $errors[] = sprintf('Required production variable is missing: %s.', $name);
    }
}

if ('prod' !== ($_SERVER['APP_ENV'] ?? $_ENV['APP_ENV'] ?? null)) {
    $errors[] = 'APP_ENV must be set to prod.';
}

if (!in_array(strtolower((string) ($_SERVER['APP_DEBUG'] ?? $_ENV['APP_DEBUG'] ?? '')), ['0', 'false', 'off', 'no'], true)) {
    $errors[] = 'APP_DEBUG must be disabled (0, false, off or no).';
}

$projectDir = dirname(__DIR__);
$requiredPaths = [
    $projectDir.'/public/index.php',
    $projectDir.'/public/assets',
    $projectDir.'/public/florie/index.html',
    $projectDir.'/public/audrey/index.html',
    $projectDir.'/vendor/autoload_runtime.php',
];

foreach ($requiredPaths as $path) {
    if (!file_exists($path)) {
        $errors[] = sprintf('Required deployment path is missing: %s.', str_replace($projectDir.'/', '', $path));
    }
}

$runtimeDir = $projectDir.'/var';
if (!is_dir($runtimeDir) || !is_writable($runtimeDir)) {
    $errors[] = 'The var/ directory must exist and be writable by PHP.';
}

if ([] !== $errors) {
    fwrite(STDERR, "Production readiness check failed:\n");
    foreach ($errors as $error) {
        fwrite(STDERR, sprintf(" - %s\n", $error));
    }

    exit(1);
}

fwrite(STDOUT, sprintf("Production readiness check passed with PHP %s.\n", PHP_VERSION));
