package com.seer.teach.ai.client.model.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.codec.json.Jackson2JsonDecoder;
import org.springframework.http.codec.json.Jackson2JsonEncoder;
import org.springframework.http.converter.json.Jackson2ObjectMapperBuilder;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.client.RestClient;
import org.springframework.web.reactive.function.client.ExchangeFilterFunction;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * DashScope API 配置类
 * 用于配置restClient以正确处理聊天完成请求
 */
@Slf4j
@Configuration
public class DashScopeClientConfig {

    /**
     * 创建用于DashScope API的RestClient
     */
    @Bean
    public RestClient aiRestClient() {
        ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
                .modules(new JavaTimeModule())
                .build();

        MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter(objectMapper);

        return RestClient.builder()
                .requestInterceptor(new LoggingInterceptor())
                .messageConverters(converters -> converters.add(converter))
                .build();
    }

    /**
     * 创建用于DashScope API的WebClient并启用日志
     */
    @Bean
    public WebClient aiWebClient() {
        ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json()
                .modules(new JavaTimeModule())
                .build();

        return WebClient.builder()
                .codecs(configurer -> configurer.defaultCodecs().jackson2JsonDecoder(new Jackson2JsonDecoder(objectMapper)))
                .codecs(configurer -> configurer.defaultCodecs().jackson2JsonEncoder(new Jackson2JsonEncoder(objectMapper)))
                .filter(ExchangeFilterFunction.ofRequestProcessor(clientRequest -> {
                    log.info("Request: {} {}", clientRequest.method(), clientRequest.url());
                    clientRequest.headers().forEach((name, values) ->
                            values.forEach(value -> log.info("{}={}", name, value)));
                    return Mono.just(clientRequest);
                }))
                .filter(ExchangeFilterFunction.ofResponseProcessor(clientResponse -> {
                    log.info("Response Status: {}", clientResponse.statusCode());
                    clientResponse.headers().asHttpHeaders().forEach((name, values) ->
                            values.forEach(value -> log.info("{}={}", name, value)));
                    return Mono.just(clientResponse);
                }))
                .build();
    }


    public static class LoggingInterceptor implements ClientHttpRequestInterceptor {

        @Override
        public ClientHttpResponse intercept(
                HttpRequest request,
                byte[] body,
                ClientHttpRequestExecution execution) throws IOException {

            // 记录请求信息
            log.info("HTTP请求方法: {}", request.getMethod());
            log.info("HTTP请求URL: {}", request.getURI());
            log.info("HTTP请求头: {}", request.getHeaders());
            if (body.length > 0) {
                log.info("HTTP请求体: {}", new String(body, StandardCharsets.UTF_8));
            }

            // 执行请求
            ClientHttpResponse response = execution.execute(request, body);

            return response;
        }
    }
}