package com.kt.ai.config;

import io.github.resilience4j.circuitbreaker.CircuitBreaker;
import io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.SlidingWindowType;
import io.github.resilience4j.circuitbreaker.CircuitBreakerRegistry;
import io.github.resilience4j.timelimiter.TimeLimiterConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.time.Duration;

/**
 * Circuit Breaker 설정
 * - Claude API / GPT-4 API 장애 대응
 * - Timeout: 5분 (300초)
 * - Failure Threshold: 50%
 *
 * @author AI Service Team
 * @since 1.0.0
 */
@Configuration
public class CircuitBreakerConfig {

    /**
     * Circuit Breaker Registry 설정
     */
    @Bean
    public CircuitBreakerRegistry circuitBreakerRegistry() {
        io.github.resilience4j.circuitbreaker.CircuitBreakerConfig config =
                io.github.resilience4j.circuitbreaker.CircuitBreakerConfig.custom()
                        .failureRateThreshold(50)
                        .slowCallRateThreshold(50)
                        .slowCallDurationThreshold(Duration.ofSeconds(60))
                        .permittedNumberOfCallsInHalfOpenState(3)
                        .maxWaitDurationInHalfOpenState(Duration.ZERO)
                        .slidingWindowType(SlidingWindowType.COUNT_BASED)
                        .slidingWindowSize(10)
                        .minimumNumberOfCalls(5)
                        .waitDurationInOpenState(Duration.ofSeconds(60))
                        .automaticTransitionFromOpenToHalfOpenEnabled(true)
                        .build();

        return CircuitBreakerRegistry.of(config);
    }

    /**
     * Claude API Circuit Breaker
     */
    @Bean
    public CircuitBreaker claudeApiCircuitBreaker(CircuitBreakerRegistry registry) {
        return registry.circuitBreaker("claudeApi");
    }

    /**
     * GPT-4 API Circuit Breaker
     */
    @Bean
    public CircuitBreaker gpt4ApiCircuitBreaker(CircuitBreakerRegistry registry) {
        return registry.circuitBreaker("gpt4Api");
    }

    /**
     * Time Limiter 설정 (5분)
     */
    @Bean
    public TimeLimiterConfig timeLimiterConfig() {
        return TimeLimiterConfig.custom()
                .timeoutDuration(Duration.ofSeconds(300))
                .build();
    }
}
