package at.procon.ted.config;

import at.procon.dip.runtime.condition.ConditionalOnRuntimeMode;
import at.procon.dip.runtime.config.RuntimeMode;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.lang.reflect.Method;
import java.util.concurrent.Executor;

/**
 * Async configuration for document vectorization processing.
 * Provides thread pool executor optimized for ML inference workloads.
 * 
 * @author Martin.Schweitzer@procon.co.at and claude.ai
 */
@Configuration
@ConditionalOnRuntimeMode(RuntimeMode.LEGACY)
@EnableAsync
@RequiredArgsConstructor
@Slf4j
public class AsyncConfig implements AsyncConfigurer {

    private final TedProcessorProperties properties;

    /**
     * Thread pool executor for async vectorization tasks.
     */
    @Bean(name = "vectorizationExecutor")
    public Executor vectorizationExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(properties.getVectorization().getThreadPoolSize());
        executor.setMaxPoolSize(properties.getVectorization().getThreadPoolSize() * 2);
        executor.setQueueCapacity(500);
        executor.setThreadNamePrefix("vectorization-");
        executor.setRejectedExecutionHandler((r, e) -> 
            log.warn("Vectorization task rejected, queue full"));
        executor.initialize();
        return executor;
    }

    /**
     * Default async executor for general async tasks.
     */
    @Override
    @Bean(name = "taskExecutor")
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(4);
        executor.setMaxPoolSize(8);
        executor.setQueueCapacity(200);
        executor.setThreadNamePrefix("async-");
        executor.initialize();
        return executor;
    }

    /**
     * Exception handler for async tasks.
     */
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncExceptionHandler();
    }

    /**
     * Handles uncaught exceptions in async methods.
     */
    @Slf4j
    private static class AsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
        @Override
        public void handleUncaughtException(Throwable ex, Method method, Object... params) {
            log.error("Async exception in method {}: {}", method.getName(), ex.getMessage(), ex);
        }
    }
}
