<?php

declare(strict_types=1);

namespace App\Application\Admin\System;

use App\Framework\Attributes\Route;
use App\Framework\Auth\Auth;
use App\Framework\Config\TypedConfiguration;
use App\Framework\Core\VersionInfo;
use App\Framework\DateTime\Clock;
use App\Framework\DI\DefaultContainer;
use App\Framework\Http\Method;
use App\Framework\Http\Session\SessionManager;
use App\Framework\Meta\MetaData;
use App\Framework\Performance\MemoryMonitor;
use App\Framework\Router\Result\ViewResult;

final readonly class SystemDashboardController
{
    public function __construct(
        private DefaultContainer $container,
        private VersionInfo $versionInfo,
        private TypedConfiguration $config,
        private MemoryMonitor $memoryMonitor,
        private Clock $clock,
    ) {
    }

    #[Auth]
    #[Route(path: '/admin/system', method: Method::GET)]
    public function show(): ViewResult
    {
        /** @var array<string, mixed> $stats */
        $stats = [
            'frameworkVersion' => $this->versionInfo->getVersion(),
            'phpVersion' => PHP_VERSION,
            'memoryUsage' => $this->memoryMonitor->getCurrentMemory()->toHumanReadable(),
            'peakMemoryUsage' => $this->memoryMonitor->getPeakMemory()->toHumanReadable(),
            'serverInfo' => $_SERVER['SERVER_SOFTWARE'] ?? 'Unknown',
            'serverTime' => $this->clock->now()->format('Y-m-d H:i:s'),
            'timezone' => date_default_timezone_get(),
            'operatingSystem' => PHP_OS,
            'loadedExtensions' => $this->getLoadedExtensions(),
            'sessionCount' => $this->getActiveSessionCount(),
            'uptime' => $this->getServerUptime(),
            'servicesCount' => 4,
        ];

        return new ViewResult(
            template: 'dashboard',
            metaData: new MetaData('System Dashboard'),
            /** @var array<string, mixed> */
            data: [
                'title' => 'System Dashboard',
                'stats' => $stats,
            ]
        );
    }

    /**
     * @return array<int, string>
     */
    private function getLoadedExtensions(): array
    {
        $extensions = get_loaded_extensions();
        sort($extensions);

        return $extensions;
    }

    private function getActiveSessionCount(): int
    {
        try {
            if ($this->container->has(SessionManager::class)) {
                $sessionManager = $this->container->get(SessionManager::class);

                return $sessionManager->getActiveSessionCount();
            }
        } catch (\Throwable $e) {
            // Silent fail
        }

        return 0;
    }

    private function getServerUptime(): string
    {
        // Für Linux-Systeme
        if (function_exists('shell_exec') && stripos(PHP_OS, 'Linux') !== false) {
            $uptime = shell_exec('uptime -p');
            if ($uptime) {
                return $uptime;
            }
        }

        // Fallback
        return 'Nicht verfügbar';
    }
}
