package com.ruoyi.agent.service;

import org.noear.solon.Solon;
import org.noear.solon.ai.chat.tool.MethodToolProvider;
import org.noear.solon.ai.mcp.server.IMcpServerEndpoint;
import org.noear.solon.ai.mcp.server.McpServerEndpointProvider;
import org.noear.solon.ai.mcp.server.annotation.McpServerEndpoint;
import org.noear.solon.ai.chat.prompt.MethodPromptProvider;
import org.noear.solon.ai.chat.resource.MethodResourceProvider;
import org.noear.solon.web.servlet.SolonServletFilter;
import org.springframework.aop.support.AopUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.AnnotationUtils;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.List;

/**
 * 这个类独立一个目录，可以让 Solon 扫描范围最小化
 * */
@Configuration
public class McpServerConfig {
    @Autowired(required=false)
    private List<IMcpServerEndpoint> serverEndpoints;
    @PostConstruct
    public void start() {
        Solon.start(McpServerConfig.class, new String[]{"--cfg=application.yml"});
        springCom2Endpoint();
    }

    @PreDestroy
    public void stop() {
        if (Solon.app() != null) {
            Solon.stopBlock(false, Solon.cfg().stopDelay());
        }
    }

    //Spring 组件转为端点
    protected void springCom2Endpoint() {
        if (serverEndpoints != null) {
            //提取实现容器里 IMcpServerEndpoint 接口的 bean ，并注册为服务端点
            for (IMcpServerEndpoint serverEndpoint : serverEndpoints) {
                Class<?> serverEndpointClz = AopUtils.getTargetClass(serverEndpoint);
                McpServerEndpoint anno = AnnotationUtils.findAnnotation(serverEndpointClz, McpServerEndpoint.class);

                if (anno == null) {
                    continue;
                }

                McpServerEndpointProvider serverEndpointProvider = McpServerEndpointProvider.builder()
                        .from(serverEndpointClz, anno)
                        .build();

                serverEndpointProvider.addTool(new MethodToolProvider(serverEndpointClz, serverEndpoint));
                serverEndpointProvider.addResource(new MethodResourceProvider(serverEndpointClz, serverEndpoint));
                serverEndpointProvider.addPrompt(new MethodPromptProvider(serverEndpointClz, serverEndpoint));

                serverEndpointProvider.postStart();

                //可以再把 serverEndpointProvider 手动转入 SpringBoot 容器
            }
        }
    }

    @Bean
    public FilterRegistrationBean mcpServerFilter() {
        FilterRegistrationBean<SolonServletFilter> filter = new FilterRegistrationBean<>();
        filter.setName("SolonFilter");
        filter.addUrlPatterns("/mcp/*");
        filter.setFilter(new SolonServletFilter());
        return filter;
    }
}