<?php

declare(strict_types=1);

namespace PpPhp\Core\Platform\Services\Blueprint;

use PpPhp\Core\Platform\Services\Descriptor\ServiceDescriptor;

final class BlueprintFactory
{
    public static function fromDescriptor(ServiceDescriptor $descriptor, array $validation = []): ServiceBlueprint
    {
        return (new BlueprintBuilder())
            ->id($descriptor->id())
            ->type('service-blueprint')
            ->label($descriptor->label())
            ->version($descriptor->version())
            ->metadata([
                'descriptorType' => $descriptor->type(),
                'description' => $descriptor->description(),
                'source' => $descriptor->source(),
                'raw' => $descriptor->toArray(),
            ])
            ->dependencies($descriptor->dependencies())
            ->capabilities($descriptor->capabilities())
            ->lifecycle($descriptor->lifecycle())
            ->visibility($descriptor->visibility())
            ->runtimePolicy([
                'lazy' => $descriptor->lazy(),
                'source' => $descriptor->source(),
            ])
            ->validation($validation)
            ->build();
    }

    public static function fromArray(array $data): ServiceBlueprint
    {
        return (new BlueprintBuilder())
            ->id((string) ($data['id'] ?? $data['identity']['id'] ?? ''))
            ->type((string) ($data['type'] ?? $data['identity']['type'] ?? 'service-blueprint'))
            ->label((string) ($data['label'] ?? $data['identity']['label'] ?? ''))
            ->version((string) ($data['version'] ?? $data['version']['version'] ?? '1.0.0'))
            ->status((string) ($data['status'] ?? $data['version']['status'] ?? 'compiled'))
            ->metadata(is_array($data['metadata'] ?? null) ? $data['metadata'] : [])
            ->dependencies(is_array($data['dependencies'] ?? null) ? $data['dependencies'] : [])
            ->capabilities(is_array($data['capabilities'] ?? null) ? $data['capabilities'] : [])
            ->lifecycle((string) ($data['lifecycle'] ?? 'singleton'))
            ->visibility((string) ($data['visibility'] ?? 'public'))
            ->runtimePolicy(is_array($data['runtimePolicy'] ?? null) ? $data['runtimePolicy'] : [])
            ->validation(is_array($data['validation'] ?? null) ? $data['validation'] : [])
            ->build();
    }
}
