<?php
declare(strict_types=1);

namespace PpPhp\Core\Platform\Developer;

use PpPhp\Core\Platform\Bootstrap\PlatformBootstrap;
use PpPhp\Core\Platform\Kernel\Facades\Runtime;
use PpPhp\Core\Platform\Kernel\Platform;

final class PlatformDoctor
{
    public function diagnose(): array
    {
        $issues = [];
        $loader = PlatformBootstrap::loader();

        if (!$loader) {
            $issues[] = ['severity' => 'error', 'message' => 'Platform class loader is not registered.'];
        }

        if (!Runtime::booted()) {
            $issues[] = ['severity' => 'warning', 'message' => 'Runtime is not booted.'];
        }

        foreach (Platform::manifests()->warnings() as $warning) {
            $issues[] = ['severity' => 'warning', 'message' => 'Manifest warning: ' . ($warning['message'] ?? 'Unknown')];
        }

        if (count(Platform::manifests()->all()) === 0) {
            $issues[] = ['severity' => 'error', 'message' => 'No manifests discovered.'];
        }

        if (Platform::modules()->count() === 0) {
            $issues[] = ['severity' => 'warning', 'message' => 'No modules discovered.'];
        }

        $classCount = $loader ? $loader->count() : 0;
        if ($classCount < 50) {
            $issues[] = ['severity' => 'warning', 'message' => 'Classmap appears unusually small.'];
        }

        $errors = count(array_filter($issues, static fn (array $i): bool => $i['severity'] === 'error'));
        $warnings = count(array_filter($issues, static fn (array $i): bool => $i['severity'] === 'warning'));

        $score = 100;
        $score -= $errors * 30;
        $score -= $warnings * 10;
        $score = max(0, $score);

        return [
            'healthScore' => $score,
            'errors' => $errors,
            'warnings' => $warnings,
            'issues' => $issues,
            'summary' => [
                'classes' => $classCount,
                'manifests' => count(Platform::manifests()->all()),
                'modules' => Platform::modules()->count(),
                'services' => count(Platform::registries()->services->all()),
            ],
        ];
    }
}
