/*
 * Copyright 2017-2025 noear.org and authors
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.noear.solon.ai.mcp.server.manager;

import io.modelcontextprotocol.json.McpJsonMapper;
import io.modelcontextprotocol.server.*;
import io.modelcontextprotocol.spec.McpSchema;
import org.noear.snack4.ONode;
import org.noear.solon.Utils;
import org.noear.solon.ai.chat.tool.FunctionTool;
import org.noear.solon.ai.mcp.exception.McpException;
import org.noear.solon.ai.mcp.server.McpServerContext;
import org.noear.solon.ai.mcp.server.McpServerProperties;
import org.noear.solon.core.handle.Context;
import reactor.core.publisher.Mono;

import java.util.Collection;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * 无状态工具注册表
 *
 * @author noear
 * @since 3.8.0
 */
public class StatelessToolRegistry implements McpPrimitivesRegistry<FunctionTool> {
    private final Map<String, FunctionTool> toolsMap = new ConcurrentHashMap<>();

    private final Supplier<McpStatelessAsyncServer> serverSupplier;
    private final McpServer.StatelessAsyncSpecification mcpServerSpec;

    public StatelessToolRegistry(Supplier<McpStatelessAsyncServer> serverSupplier, McpServer.StatelessAsyncSpecification mcpServerSpec) {
        this.serverSupplier = serverSupplier;
        this.mcpServerSpec = mcpServerSpec;
    }

    @Override
    public int count() {
        return toolsMap.size();
    }

    @Override
    public Collection<FunctionTool> all() {
        return toolsMap.values();
    }

    @Override
    public boolean contains(String toolName) {
        return toolsMap.containsKey(toolName);
    }

    @Override
    public void remove(String toolName) {
        if (serverSupplier.get() != null) {
            serverSupplier.get().removeTool(toolName).block();
            toolsMap.remove(toolName);
        }
    }

    @Override
    public void add(McpServerProperties mcpServerProps, FunctionTool functionTool) {
        try {
            //内部登记
            toolsMap.put(functionTool.name(), functionTool);

            // 构建 inputSchema JSON 字符串
            String inSchemaJson = buildJsonSchema(functionTool).toJson();

            McpSchema.ToolAnnotations toolAnnotations = McpSchema.ToolAnnotations.builder()
                    .returnDirect(functionTool.returnDirect())
                    .build();


            McpSchema.Tool.Builder toolBuilder = McpSchema.Tool.builder()
                    .name(functionTool.name()).title(functionTool.title()).description(functionTool.description())
                    .meta(functionTool.meta())
                    .annotations(toolAnnotations)
                    .inputSchema(McpJsonMapper.getDefault(), inSchemaJson);

            if (mcpServerProps.isEnableOutputSchema() && Utils.isNotEmpty(functionTool.outputSchema())) {
                toolBuilder.outputSchema(McpJsonMapper.getDefault(), functionTool.outputSchema());
            }

            // 注册实际调用逻辑
            McpStatelessServerFeatures.AsyncToolSpecification toolSpec = new McpStatelessServerFeatures.AsyncToolSpecification(
                    toolBuilder.build(),
                    (exchange, request) -> {
                        return Mono.create(sink -> {
                            Context.currentWith(new McpServerContext(null, exchange), () -> {
                                functionTool.handleAsync(request.arguments()).whenComplete((rst, err) -> {
                                    McpResultResponder.doToolResultResponse(sink, mcpServerProps, functionTool, rst, err);
                                });
                            });
                        });
                    });

            if (serverSupplier.get() != null) {
                serverSupplier.get().addTool(toolSpec).block();
            } else {
                mcpServerSpec.tools(toolSpec).build();
            }
        } catch (Throwable ex) {
            throw new McpException("Tool add failed, tool: " + functionTool.name(), ex);
        }
    }

    protected ONode buildJsonSchema(FunctionTool functionTool) {
        ONode jsonSchema = new ONode();
        jsonSchema.set("$schema", "http://json-schema.org/draft-07/schema#");
        jsonSchema.setAll(ONode.ofJson(functionTool.inputSchema()).getObject());

        return jsonSchema;
    }
}