<?php
declare(strict_types=1);

namespace App\Services;

final class RuntimeEnvironmentService
{
    /** @return array<string,mixed> */
    public function report(): array
    {
        $required = ['pdo_mysql', 'json', 'mbstring', 'openssl', 'fileinfo', 'zip'];
        $extensions = [];
        foreach ($required as $extension) {
            $extensions[$extension] = extension_loaded($extension) || ($extension === 'zip' && class_exists(\ZipArchive::class));
        }

        $rootFree = @disk_free_space(BASE_PATH);
        $rootTotal = @disk_total_space(BASE_PATH);
        $freeBytes = is_float($rootFree) || is_int($rootFree) ? (int)$rootFree : 0;
        $totalBytes = is_float($rootTotal) || is_int($rootTotal) ? (int)$rootTotal : 0;
        $freePercent = $totalBytes > 0 ? round(($freeBytes / $totalBytes) * 100, 1) : null;

        $warnings = [];
        if (version_compare(PHP_VERSION, '8.1.0', '<')) {
            $warnings[] = 'PHP 8.1 minimum requis.';
        }
        foreach ($extensions as $name => $loaded) {
            if (!$loaded) {
                $warnings[] = 'Extension PHP absente : ' . $name;
            }
        }
        if ($freePercent !== null && $freePercent < 10) {
            $warnings[] = 'Espace disque disponible inférieur à 10 %.';
        }

        return [
            'status' => $warnings === [] ? 'ok' : 'warning',
            'php_version' => PHP_VERSION,
            'sapi' => PHP_SAPI,
            'os' => PHP_OS_FAMILY,
            'memory_limit' => (string)ini_get('memory_limit'),
            'upload_max_filesize' => (string)ini_get('upload_max_filesize'),
            'post_max_size' => (string)ini_get('post_max_size'),
            'max_execution_time' => (string)ini_get('max_execution_time'),
            'timezone' => (string)date_default_timezone_get(),
            'extensions' => $extensions,
            'disk_free_bytes' => $freeBytes,
            'disk_total_bytes' => $totalBytes,
            'disk_free_percent' => $freePercent,
            'warnings' => $warnings,
        ];
    }
}
