<?php

declare(strict_types=1);

namespace App\Filament\System\Widgets;

use App\Models\OperationRun;
use App\Support\OperationRunOutcome;
use App\Support\OperationRunStatus;
use App\Support\SystemConsole\StuckRunClassifier;
use Carbon\CarbonImmutable;
use Filament\Widgets\Widget;

class ControlTowerHealthIndicator extends Widget
{
    protected string $view = 'filament.system.widgets.control-tower-health-indicator';

    protected static bool $isLazy = false;

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

    /**
     * @return array{level: string, color: string, icon: string, label: string, failed: int, stuck: int}
     */
    public function getHealthData(): array
    {
        $now = CarbonImmutable::now();
        $last24h = $now->subHours(24);

        $failedRuns = OperationRun::query()
            ->where('created_at', '>=', $last24h)
            ->where('status', OperationRunStatus::Completed->value)
            ->where('outcome', OperationRunOutcome::Failed->value)
            ->count();

        $stuckRuns = app(StuckRunClassifier::class)
            ->apply(OperationRun::query())
            ->count();

        if ($failedRuns > 0 || $stuckRuns > 0) {
            $level = ($failedRuns >= 5 || $stuckRuns >= 3) ? 'critical' : 'warning';
        } else {
            $level = 'healthy';
        }

        return match ($level) {
            'critical' => [
                'level' => 'critical',
                'color' => 'danger',
                'icon' => 'heroicon-o-x-circle',
                'label' => 'Critical',
                'failed' => $failedRuns,
                'stuck' => $stuckRuns,
            ],
            'warning' => [
                'level' => 'warning',
                'color' => 'warning',
                'icon' => 'heroicon-o-exclamation-triangle',
                'label' => 'Attention needed',
                'failed' => $failedRuns,
                'stuck' => $stuckRuns,
            ],
            default => [
                'level' => 'healthy',
                'color' => 'success',
                'icon' => 'heroicon-o-check-circle',
                'label' => 'All systems healthy',
                'failed' => 0,
                'stuck' => 0,
            ],
        };
    }
}
