<?php

namespace App\Filament\Widgets\Server;

use Filament\Widgets\Widget;

class ServerSummaryWidget extends Widget
{
    protected string $view = 'filament.widgets.server.server-summary';

    protected int|string|array $columnSpan = 1;

    protected static ?int $sort = 2;

    /**
     * @return array<string, mixed>
     */
    public function getSummary(): array
    {
        $cpuInfo = @file_get_contents('/proc/cpuinfo');

        $summary = [
            'Operating System' => PHP_OS_FAMILY,
            'Architecture' => php_uname('m'),
        ];

        // CPU info (Linux)
        if (PHP_OS_FAMILY === 'Linux') {
            if ($cpuInfo) {
                preg_match('/model name\s*:\s*(.+)/i', $cpuInfo, $modelMatch);
                preg_match('/cpu cores\s*:\s*(\d+)/i', $cpuInfo, $coresMatch);
                preg_match_all('/^processor/m', $cpuInfo, $processorMatches);

                if (isset($modelMatch[1])) {
                    $summary['CPU'] = trim($modelMatch[1]);
                }
                $cores = $coresMatch[1] ?? '?';
                $threads = count($processorMatches[0]) ?: '?';
                $summary['CPU Cores/Threads'] = "{$cores} cores / {$threads} threads";
            }

            // Memory
            $memInfo = @file_get_contents('/proc/meminfo');
            if ($memInfo) {
                preg_match('/MemTotal:\s*(\d+)\s*kB/i', $memInfo, $totalMatch);
                preg_match('/MemAvailable:\s*(\d+)\s*kB/i', $memInfo, $availMatch);

                if (isset($totalMatch[1]) && isset($availMatch[1])) {
                    $total = (int) $totalMatch[1] * 1024;
                    $available = (int) $availMatch[1] * 1024;
                    $used = $total - $available;
                    $percent = round(($used / $total) * 100);
                    $summary['Memory'] = $this->formatBytes($used).' / '.$this->formatBytes($total)." ({$percent}% used)";
                }
            }

            // Load average
            $loadAvg = sys_getloadavg();
            if ($loadAvg !== false) {
                $summary['Load Average'] = round($loadAvg[0], 2).' / '.round($loadAvg[1], 2).' / '.round($loadAvg[2], 2);
            }

            // Uptime
            $uptime = @file_get_contents('/proc/uptime');
            if ($uptime) {
                $seconds = (int) explode(' ', $uptime)[0];
                $summary['Uptime'] = $this->formatUptime($seconds);
            }
        }

        // PHP & Laravel (versions obscured for security)
        $summary['PHP Version'] = $this->obscureVersion(PHP_VERSION).' ('.PHP_SAPI.')';
        $summary['Laravel Version'] = $this->obscureVersion(app()->version());
        $summary['Debug Mode'] = config('app.debug') ? 'Enabled' : 'Disabled';

        return $summary;
    }

    protected function obscureVersion(string $version): string
    {
        $parts = explode('.', $version);
        if (count($parts) >= 2) {
            return $parts[0].'.'.$parts[1].'.x';
        }

        return $version;
    }

    protected function formatBytes(int $bytes): string
    {
        $units = ['B', 'KB', 'MB', 'GB', 'TB'];
        $i = 0;

        while ($bytes >= 1024 && $i < count($units) - 1) {
            $bytes /= 1024;
            $i++;
        }

        return round($bytes, 1).' '.$units[$i];
    }

    protected function formatUptime(int $seconds): string
    {
        $days = floor($seconds / 86400);
        $hours = floor(($seconds % 86400) / 3600);
        $minutes = floor(($seconds % 3600) / 60);

        $parts = [];
        if ($days > 0) {
            $parts[] = $days.' day'.($days > 1 ? 's' : '');
        }
        if ($hours > 0) {
            $parts[] = $hours.' hr'.($hours > 1 ? 's' : '');
        }
        if ($minutes > 0 && $days < 1) {
            $parts[] = $minutes.' min';
        }

        return implode(', ', $parts) ?: '< 1 min';
    }
}
