package tech.easyflow.agent.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Agent 文档读取独立有界线程池配置。
 */
@Configuration
public class AgentDocumentReaderConfig {

    /**
     * 创建文档读取线程池；队列满时直接拒绝，避免任务回落到调用线程。
     *
     * @param properties 文档配置
     * @return 文档读取执行器
     */
    @Bean(name = "agentDocumentReaderExecutor", destroyMethod = "shutdown")
    public ExecutorService agentDocumentReaderExecutor(AgentDocumentProperties properties) {
        AgentDocumentProperties.Reader reader = properties.getReader();
        return new ThreadPoolExecutor(
                reader.getCoreSize(),
                reader.getMaxSize(),
                60L,
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<>(reader.getQueueCapacity()),
                new ReaderThreadFactory(),
                new ThreadPoolExecutor.AbortPolicy());
    }

    /**
     * 文档读取线程命名工厂。
     */
    private static final class ReaderThreadFactory implements ThreadFactory {

        private final AtomicInteger index = new AtomicInteger(1);

        /**
         * 创建守护读取线程。
         *
         * @param runnable 读取任务
         * @return 命名线程
         */
        @Override
        public Thread newThread(Runnable runnable) {
            Thread thread = new Thread(runnable);
            thread.setName("agent-document-reader-" + index.getAndIncrement());
            thread.setDaemon(true);
            return thread;
        }
    }
}
