/*
 * 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.server.McpAsyncServer;
import io.modelcontextprotocol.server.McpServer;
import io.modelcontextprotocol.server.McpServerFeatures;
import io.modelcontextprotocol.spec.McpSchema;
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.ai.chat.prompt.FunctionPrompt;
import org.noear.solon.ai.util.ParamDesc;
import org.noear.solon.core.handle.Context;
import reactor.core.publisher.Mono;

import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.function.Supplier;

/**
 * 有状态提示词注册表
 *
 * @author noear
 * @since 3.2
 */
public class StatefulPromptRegistry implements McpPrimitivesRegistry<FunctionPrompt> {
    private final Map<String, FunctionPrompt> promptsMap = new ConcurrentHashMap<>();

    private final Supplier<McpAsyncServer> serverSupplier;
    private final McpServer.AsyncSpecification mcpServerSpec;

    public StatefulPromptRegistry(Supplier<McpAsyncServer> serverSupplier, McpServer.AsyncSpecification mcpServerSpec) {
        this.serverSupplier = serverSupplier;
        this.mcpServerSpec = mcpServerSpec;
    }


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

    @Override
    public Collection<FunctionPrompt> all() {
        return promptsMap.values();
    }

    @Override
    public boolean contains(String promptName) {
        return promptsMap.containsKey(promptName);
    }

    @Override
    public void remove(String promptName) {
        if (serverSupplier.get() != null) {
            serverSupplier.get().removePrompt(promptName).block();
            promptsMap.remove(promptName);
        }
    }

    @Override
    public void add(McpServerProperties mcpServerProps, FunctionPrompt functionPrompt) {
        try {
            promptsMap.put(functionPrompt.name(), functionPrompt);

            List<McpSchema.PromptArgument> promptArguments = new ArrayList<>();
            for (ParamDesc p1 : functionPrompt.params()) {
                promptArguments.add(new McpSchema.PromptArgument(p1.name(), p1.description(), p1.required()));
            }

            McpServerFeatures.AsyncPromptSpecification promptSpec = new McpServerFeatures.AsyncPromptSpecification(
                    McpSchema.Prompt.builder()
                            .name(functionPrompt.name()).title(functionPrompt.title()).description(functionPrompt.description())
                            .meta(functionPrompt.meta())
                            .arguments(promptArguments)
                            .build(),
                    (exchange, request) -> {
                        return Mono.create(sink -> {
                            Context.currentWith(new McpServerContext(exchange, exchange.transportContext()), () -> {
                                functionPrompt.handleAsync(request.arguments()).whenComplete((rst, err) -> {
                                    McpResultResponder.doPromptResultResponse(sink, mcpServerProps, functionPrompt, rst, err);
                                });
                            });
                        });
                    });

            if (serverSupplier.get() != null) {
                serverSupplier.get().addPrompt(promptSpec).block();
            } else {
                mcpServerSpec.prompts(promptSpec).build();
            }
        } catch (Throwable ex) {
            throw new McpException("Prompt add failed, prompt: " + functionPrompt.name(), ex);
        }
    }
}