<?php

namespace App\Filament\Widgets;

use App\Services\Dokploy\DokployClient;
use Filament\Widgets\Widget;
use Illuminate\Support\Arr;

class DokployPlatformHealth extends Widget
{
    protected string $view = 'filament.widgets.dokploy-platform-health';

    protected ?string $pollingInterval = '60s';

    protected function getViewData(): array
    {
        return [
            'composes' => $this->loadComposes(),
        ];
    }

    protected function loadComposes(): array
    {
        $client = app(DokployClient::class);
        $composeMap = config('dokploy.composes', []);
        $results = [];

        foreach ($composeMap as $label => $composeId) {
            try {
                $status = $client->composeStatus($composeId);
                $deployments = $client->composeDeployments($composeId, 1);
                $compose = Arr::get($status, 'compose', []);
                $services = $this->formatServices(Arr::get($status, 'services', []));

                $results[] = [
                    'label' => ucfirst($label),
                    'compose_id' => $composeId,
                    'name' => Arr::get($compose, 'name') ?? Arr::get($compose, 'appName') ?? $composeId,
                    'status' => Arr::get($compose, 'composeStatus', 'unknown'),
                    'services' => $services,
                    'last_deploy' => Arr::get($deployments, '0.createdAt')
                        ?? Arr::get($deployments, '0.created_at')
                        ?? Arr::get($compose, 'updatedAt')
                        ?? Arr::get($compose, 'lastDeploymentAt'),
                ];
            } catch (\Throwable $exception) {
                $results[] = [
                    'label' => ucfirst($label),
                    'compose_id' => $composeId,
                    'name' => $composeId,
                    'status' => 'unreachable',
                    'error' => $exception->getMessage(),
                    'services' => [],
                    'last_deploy' => null,
                ];
            }
        }

        if (empty($results)) {
            return [
                [
                    'label' => 'Dokploy',
                    'compose_id' => '-',
                    'status' => 'unconfigured',
                    'error' => 'Set DOKPLOY_COMPOSE_IDS in .env to enable monitoring.',
                ],
            ];
        }

        return $results;
    }

    protected function formatServices(array $services): array
    {
        return collect($services)
            ->map(function ($service) {
                return [
                    'name' => Arr::get($service, 'serviceName') ?? Arr::get($service, 'name') ?? Arr::get($service, 'containerName'),
                    'status' => Arr::get($service, 'status') ?? Arr::get($service, 'state') ?? Arr::get($service, 'composeStatus', 'unknown'),
                ];
            })
            ->filter(fn ($service) => filled($service['name']))
            ->values()
            ->all();
    }
}
