package cn.meowrain.aioj.backend.aiservice.config;

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.netty.shaded.io.grpc.netty.NettyChannelBuilder;
import cn.meowrain.aioj.backend.aiservice.grpc.AIServiceGrpc;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

/**
 * gRPC 客户端配置
 */
@Slf4j
@Configuration
public class GrpcClientConfiguration {

    private final GrpcClientProperties properties;
    private ManagedChannel channel;

    public GrpcClientConfiguration(GrpcClientProperties properties) {
        this.properties = properties;
    }

    /**
     * 创建 gRPC ManagedChannel
     */
    @Bean
    @Qualifier("aiServiceChannel")
    public ManagedChannel aiServiceChannel() {
        log.info("Initializing gRPC channel to {}:{}", properties.getHost(), properties.getPort());

        NettyChannelBuilder builder = NettyChannelBuilder
                .forAddress(properties.getHost(), properties.getPort())
                .maxInboundMessageSize(properties.getMaxMessageSize());

        if (properties.isTlsEnabled()) {
            builder.useTransportSecurity();
        } else {
            builder.usePlaintext();
        }

        this.channel = builder.build();
        return channel;
    }

    /**
     * 创建 AI Service gRPC 客户端存根
     */
    @Bean
    public AIServiceGrpc.AIServiceBlockingStub aiServiceBlockingStub(
            @Qualifier("aiServiceChannel") ManagedChannel channel) {
        log.info("Creating AI Service gRPC blocking stub");
        return AIServiceGrpc.newBlockingStub(channel)
                .withDeadlineAfter(properties.getTimeout(), TimeUnit.SECONDS);
    }

    /**
     * 创建 AI Service gRPC 异步客户端存根
     */
    @Bean
    public AIServiceGrpc.AIServiceStub aiServiceStub(
            @Qualifier("aiServiceChannel") ManagedChannel channel) {
        log.info("Creating AI Service gRPC async stub");
        return AIServiceGrpc.newStub(channel)
                .withDeadlineAfter(properties.getTimeout(), TimeUnit.SECONDS);
    }

    /**
     * 应用关闭时清理资源
     */
    @PreDestroy
    public void destroy() {
        if (channel != null && !channel.isShutdown()) {
            log.info("Shutting down gRPC channel");
            try {
                channel.shutdown().awaitTermination(5, TimeUnit.SECONDS);
            } catch (InterruptedException e) {
                log.error("Error shutting down gRPC channel", e);
                channel.shutdownNow();
            }
        }
    }
}
