<?php

namespace Modules\AiCore\Entities\Services;

use Modules\AiCore\Entities\Contracts\AiTool;

/**
 * Process-wide registry of AiTools.
 *
 * Modules register their tools here (typically from a service provider or just
 * before invoking the AI), keyed by the tool's name(). Consumers then pull the
 * specific, gated tools they want to offer for a given interaction and pass
 * that explicit whitelist to the {@see ToolRunner}.
 *
 * Bound as a singleton in AiCoreServiceProvider so registrations persist for
 * the request. Registering the same name twice replaces the earlier tool.
 */
class AiToolRegistry
{
    /** @var array<string,AiTool> */
    private array $tools = [];

    public function register(AiTool $tool): self
    {
        $this->tools[$tool->name()] = $tool;
        return $this;
    }

    public function has(string $name): bool
    {
        return isset($this->tools[$name]);
    }

    public function get(string $name): ?AiTool
    {
        return $this->tools[$name] ?? null;
    }

    /**
     * Return the registered tool instances for the given names, in order.
     * Names with no registered tool are silently skipped.
     *
     * @param string[] $names
     * @return AiTool[]
     */
    public function only(array $names): array
    {
        $out = [];
        foreach ($names as $name) {
            if (isset($this->tools[$name])) {
                $out[] = $this->tools[$name];
            }
        }
        return $out;
    }

    /** @return array<string,AiTool> */
    public function all(): array
    {
        return $this->tools;
    }
}
