package org.dromara.ai.config;

import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

// springdoc group
// Use class name to avoid hard dependency if springdoc is absent at compile-time
@Configuration
@EnableConfigurationProperties(AiGatewayProperties.class)
public class AiApiConfig {

    @Bean
    public Object aiGroupedOpenApi() {
        try {
            Class<?> groupedOpenApiClass = Class.forName("org.springdoc.core.models.GroupedOpenApi");
            return groupedOpenApiClass
                    .getMethod("builder")
                    .invoke(null)
                    .getClass()
                    .getMethod("group", String.class)
                    .invoke(
                            groupedOpenApiClass.getMethod("builder").invoke(null),
                            "AI"
                    )
                    .getClass()
                    .getMethod("packagesToScan", String[].class)
                    .invoke(
                            groupedOpenApiClass.getMethod("builder").invoke(null)
                                    .getClass().getMethod("group", String.class)
                                    .invoke(groupedOpenApiClass.getMethod("builder").invoke(null), "AI"),
                            (Object) new String[]{"org.dromara.ai.api"}
                    )
                    .getClass()
                    .getMethod("build")
                    .invoke(
                            groupedOpenApiClass.getMethod("builder").invoke(null)
                                    .getClass().getMethod("group", String.class)
                                    .invoke(groupedOpenApiClass.getMethod("builder").invoke(null), "AI")
                                    .getClass().getMethod("packagesToScan", String[].class)
                                    .invoke(
                                            groupedOpenApiClass.getMethod("builder").invoke(null)
                                                    .getClass().getMethod("group", String.class)
                                                    .invoke(groupedOpenApiClass.getMethod("builder").invoke(null), "AI"),
                                            (Object) new String[]{"org.dromara.ai.api"}
                                    )
                    );
        } catch (Throwable ignore) {
            return new Object();
        }
    }
}

