<?php

declare(strict_types=1);

namespace PpPhp\Core\Discovery\Providers;

use PpPhp\Core\Discovery\Contracts\DiscoveryProviderInterface;
use PpPhp\Core\Discovery\DiscoveryItem;
use PpPhp\Core\Discovery\DiscoveryResult;
use PpPhp\Core\Manifest\ManifestDiscovery;

final class UniversalManifestDiscoveryProvider implements DiscoveryProviderInterface
{
    public function id(): string
    {
        return 'universal-manifest';
    }

    public function label(): string
    {
        return 'Universal Manifest Discovery';
    }

    public function priority(): int
    {
        return 10;
    }

    public function discover(string $basePath): DiscoveryResult
    {
        $result = new DiscoveryResult();
        $discovery = new ManifestDiscovery();
        $manifestResult = $discovery->discover($basePath);

        foreach ($manifestResult->manifests() as $manifest) {
            $result->add(new DiscoveryItem(
                type: $manifest->type(),
                id: $manifest->id(),
                path: dirname($manifest->path()),
                metadata: $manifest->toArray()
            ));
        }

        foreach ($manifestResult->errors() as $error) {
            $result->error($error);
        }

        return $result;
    }
}
