<?php

declare(strict_types=1);

namespace Plugin\tnt_mcp\src\Mcp\Tools;

use Plugin\tnt_mcp\src\Mcp\Contracts\Tool;
use Plugin\tnt_mcp\src\Mcp\Mode\EndpointClass;
use Plugin\tnt_mcp\src\Mcp\Settings\SettingDescriber;
use Plugin\tnt_mcp\src\Mcp\Settings\SettingsRegistry;
use RuntimeException;

/** READ tool: metadata for one setting (label, description, input type, allowed values, …). */
final class DescribeSetting implements Tool
{
    /**
     * @param \Closure(): SettingDescriber $describerFactory built lazily — see {@see
     *                                                        \Plugin\tnt_mcp\src\Mcp\Tools\GetSetting}
     *                                                        for why.
     */
    public function __construct(
        private readonly SettingsRegistry $registry,
        private readonly \Closure $describerFactory,
    ) {
    }

    public function name(): string
    {
        return 'describe_setting';
    }

    public function description(): string
    {
        return 'Describe one shop setting by its key: human label, description, input type and ' .
            'allowed/current/default value where the shop exposes them.';
    }

    /** @return array<string,mixed> */
    public function inputSchema(): array
    {
        return [
            'type'                 => 'object',
            'properties'           => ['key' => ['type' => 'string']],
            'required'             => ['key'],
            'additionalProperties' => false,
        ];
    }

    public function isWrite(): bool
    {
        return false;
    }

    public function scope(): string
    {
        return 'settings:read';
    }

    public function endpointClass(): EndpointClass
    {
        return EndpointClass::Reversible;
    }

    /**
     * @param array<string,mixed> $args
     * @return array<string,mixed>
     */
    public function run(array $args): array
    {
        $key = $args['key'] ?? null;
        if (!\is_string($key) || $key === '') {
            throw new RuntimeException('describe_setting: "key" is required');
        }
        if (!$this->registry->has($key)) {
            throw new RuntimeException('describe_setting: unknown setting "' . $key . '"');
        }

        $describer = ($this->describerFactory)();

        return $describer->describe($this->registry->get($key));
    }
}
