<?php

declare(strict_types=1);

namespace App\Framework\Mcp;

use App\Framework\DI\Container;
use App\Framework\DI\Initializer;
use App\Framework\Discovery\Results\DiscoveryRegistry;

final readonly class McpInitializer
{
    public function __construct(
        private Container $container,
        private DiscoveryRegistry $discoveryResults,
    ) {
    }

    #[Initializer]
    public function __invoke(): McpServer
    {
        $toolResults = $this->discoveryResults->attributes()->get(McpTool::class);
        $resourceResults = $this->discoveryResults->attributes()->get(McpResource::class);

        // Extract mapped data from discovery results (using DiscoveredAttribute structure)
        $tools = [];
        foreach ($toolResults as $discoveredAttribute) {
            if ($discoveredAttribute->additionalData) {
                // Use the additional data from the mapper
                $tools[] = $discoveredAttribute->additionalData;
            }
        }

        $resources = [];
        foreach ($resourceResults as $discoveredAttribute) {
            if ($discoveredAttribute->additionalData) {
                // Use the additional data from the mapper
                $resources[] = $discoveredAttribute->additionalData;
            }
        }

        $toolRegistry = new McpToolRegistry($tools);
        $resourceRegistry = new McpResourceRegistry($resources);

        return new McpServer(
            $this->container,
            $toolRegistry,
            $resourceRegistry
        );
    }
}
