package com.seer.teach.teacher.common.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.web.servlet.config.annotation.AsyncSupportConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 全局异步线程池与 MVC 异步支持配置
 *
 * 解决：
 *  - Streaming through a reactive type requires an Executor to write to the response.
 *  - 提供日志与异步任务共用线程池
 *
 * @author Captain
 * @since 2025-09-10
 */
@Slf4j
@Configuration
public class AsyncConfig implements WebMvcConfigurer {

    /**
     * 【业务异步日志线程池】
     * 用于系统日志或异步任务等场景
     */
    @Bean("logExecutor")
    public Executor logExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(20);
        executor.setQueueCapacity(200);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("log-async-");

        // 拒绝策略：调用者线程执行，避免任务丢失
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        log.info("初始化异步线程池 [logExecutor]：corePoolSize={}, maxPoolSize={}, queueCapacity={}",
                executor.getCorePoolSize(), executor.getMaxPoolSize(), executor.getQueueCapacity());
        // JVM 优雅关闭钩子
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            log.info("正在关闭异步线程池 [logExecutor]...");
            executor.shutdown();
            log.info("异步线程池 [logExecutor] 已关闭");
        }));

        return executor;
    }

    @Bean("llmExecutor")
    public Executor llmExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        int cores = Runtime.getRuntime().availableProcessors();
        executor.setCorePoolSize(cores * 2);
        executor.setMaxPoolSize(cores * 4);
        executor.setQueueCapacity(500);
        executor.setKeepAliveSeconds(60);
        executor.setThreadNamePrefix("llm-async-");
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        executor.initialize();
        return executor;
    }

    /**
     * 【MVC 异步任务执行器】
     * 支持 Controller 中返回 Flux / Callable / DeferredResult
     */
    @Override
    public void configureAsyncSupport(AsyncSupportConfigurer configurer) {
        ThreadPoolTaskExecutor mvcExecutor = new ThreadPoolTaskExecutor();
        mvcExecutor.setCorePoolSize(8);
        mvcExecutor.setMaxPoolSize(32);
        mvcExecutor.setQueueCapacity(200);
        mvcExecutor.setKeepAliveSeconds(60);
        mvcExecutor.setThreadNamePrefix("mvc-async-");
        mvcExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        mvcExecutor.initialize();
        configurer.setTaskExecutor(mvcExecutor);
        configurer.setDefaultTimeout(60_000L);

        log.info("已配置 MVC 异步支持线程池 [mvc-async-]：corePoolSize={}, maxPoolSize={}, queueCapacity={}",
                mvcExecutor.getCorePoolSize(), mvcExecutor.getMaxPoolSize(), mvcExecutor.getQueueCapacity());
    }
}
