<?php

declare(strict_types=1);

namespace App\Filament\Admin\Widgets;

use App\Services\Agent\AgentClient;
use Filament\Widgets\Widget;

class ServerChartsWidget extends Widget
{
    protected string $view = 'filament.admin.widgets.server-charts';

    protected int | string | array $columnSpan = 'full';

    protected ?string $pollingInterval = '10s';

    public int $refreshKey = 0;

    public function refreshData(): void
    {
        $this->refreshKey++;
        $data = $this->getData();
        $this->dispatch('server-charts-updated', [
            'cpu' => $data['cpu']['usage'] ?? 0,
            'memory' => $data['memory']['usage'] ?? 0,
            'disk' => $data['disk']['partitions'][0]['usage_percent'] ?? 0,
        ]);
    }

    public function getData(): array
    {
        try {
            $agent = new AgentClient();
            $overview = $agent->metricsOverview();
            $disk = $agent->metricsDisk()['data'] ?? [];

            $cpu = $overview['cpu'] ?? [];
            $memory = $overview['memory'] ?? [];

            // Calculate memory usage if not provided
            $memUsage = $memory['usage_percent'] ?? $memory['usage'] ?? 0;
            if ($memUsage == 0 && ($memory['total'] ?? 0) > 0) {
                $memUsage = (($memory['used'] ?? 0) / $memory['total']) * 100;
            }

            return [
                'cpu' => [
                    'usage' => round($cpu['usage'] ?? 0, 1),
                    'cores' => $cpu['cores'] ?? 0,
                    'model' => $cpu['model'] ?? 'Unknown',
                ],
                'memory' => [
                    'usage' => round($memUsage, 1),
                    'used' => $memory['used'] ?? 0,
                    'total' => $memory['total'] ?? 0,
                    'free' => $memory['free'] ?? 0,
                    'cached' => $memory['cached'] ?? 0,
                ],
                'disk' => [
                    'partitions' => $disk['partitions'] ?? [],
                ],
                'load' => $overview['load'] ?? [],
                'uptime' => $overview['uptime']['human'] ?? 'N/A',
            ];
        } catch (\Exception $e) {
            return [
                'error' => $e->getMessage(),
                'cpu' => ['usage' => 0, 'cores' => 0, 'model' => 'Error'],
                'memory' => ['usage' => 0, 'used' => 0, 'total' => 0, 'free' => 0, 'cached' => 0],
                'disk' => ['partitions' => []],
                'load' => [],
                'uptime' => 'N/A',
            ];
        }
    }
}
