<?php

declare(strict_types=1);

namespace App\Framework\Exception;

final readonly class SystemContext
{
    public function __construct(
        public ?string $memoryUsage = null,
        public ?float $executionTime = null,
        public ?string $phpVersion = null,
        public ?string $frameworkVersion = null,
        public array $environment = []
    ) {}

    public static function current(): self
    {
        return new self(
            memoryUsage: self::formatBytes(memory_get_usage(true)),
            executionTime: isset($_SERVER['REQUEST_TIME_FLOAT'])
                ? microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']
                : null,
            phpVersion: PHP_VERSION,
            frameworkVersion: '1.0.0', // Aus Config laden
            environment: [
                'os' => PHP_OS,
                'sapi' => PHP_SAPI,
                'timezone' => date_default_timezone_get(),
                'memory_limit' => ini_get('memory_limit'),
                'max_execution_time' => ini_get('max_execution_time')
            ]
        );
    }

    public static function empty(): self
    {
        return new self();
    }

    public function toArray(): array
    {
        return [
            'memory_usage' => $this->memoryUsage,
            'execution_time' => $this->executionTime,
            'php_version' => $this->phpVersion,
            'framework_version' => $this->frameworkVersion,
            'environment' => $this->environment
        ];
    }

    private static function formatBytes(int $bytes): string
    {
        $units = ['B', 'KB', 'MB', 'GB'];
        $bytes = max($bytes, 0);
        $pow = floor(($bytes ? log($bytes) : 0) / log(1024));
        $pow = min($pow, count($units) - 1);

        $bytes /= (1 << (10 * $pow));

        return round($bytes, 2) . ' ' . $units[$pow];
    }
}
