package com.liquidnet.common.swagger.config;

import com.liquidnet.common.swagger.annotation.ApiLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import springfox.documentation.service.StringVendorExtension;
import springfox.documentation.service.VendorExtension;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.OperationBuilderPlugin;
import springfox.documentation.spi.service.contexts.OperationContext;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * Swagger插件 - 将ApiLevel信息显示在Swagger文档中
 * 
 * @author system
 * @since 2024-10-29
 */
@Component
@Order(1000)
@Slf4j
public class ApiLevelSwaggerPlugin implements OperationBuilderPlugin {
    
    @Override
    public void apply(OperationContext context) {
        // 获取方法上的ApiLevel注解
        Optional<ApiLevel> methodApiLevel = context.findAnnotation(ApiLevel.class);
        
        // 如果方法上没有，尝试获取类上的注解（继承逻辑）
        if (!methodApiLevel.isPresent()) {
            methodApiLevel = context.findControllerAnnotation(ApiLevel.class);
        }
        
        // 获取当前的notes（描述）
        String currentNotes = context.operationBuilder().build().getNotes();
        String levelInfo;
        
        if (methodApiLevel.isPresent()) {
            ApiLevel apiLevel = methodApiLevel.get();
            
            // 所有配置的级别都是正常的分级，包括L0
            levelInfo = String.format("【接口级别：%s - %s】", 
                apiLevel.level().name(), 
                apiLevel.level().getDesc());
            
            if (apiLevel.description() != null && !apiLevel.description().isEmpty()) {
                levelInfo += " " + apiLevel.description();
            }
            
            addExtensions(context, apiLevel.level().name(), apiLevel.level().getDesc(), 
                        apiLevel.level().getDetail(), apiLevel.description());
        } else {
            // 完全没有注解的情况，使用L99级别
            ApiLevel.Level unconfiguredLevel = ApiLevel.Level.L99;
            levelInfo = String.format("【接口级别：%s - %s】", 
                unconfiguredLevel.name(), 
                unconfiguredLevel.getDesc());
            
            addExtensions(context, unconfiguredLevel.name(), unconfiguredLevel.getDesc(), 
                        unconfiguredLevel.getDetail(), null);
        }
        
        // 将级别信息添加到notes中
        String newNotes = currentNotes != null ? 
            levelInfo + "\n\n" + currentNotes : levelInfo;
        
        context.operationBuilder().notes(newNotes);
    }
    
    /**
     * 添加扩展字段到Swagger JSON
     */
    private void addExtensions(OperationContext context, String level, String levelDesc, 
                              String levelDetail, String description) {
        try {
            List<VendorExtension> extensions = new ArrayList<>();
            extensions.add(new StringVendorExtension("x-api-level", level));
            extensions.add(new StringVendorExtension("x-api-level-desc", levelDesc));
            extensions.add(new StringVendorExtension("x-api-level-detail", levelDetail));
            
            if (description != null && !description.trim().isEmpty()) {
                extensions.add(new StringVendorExtension("x-api-description", description));
            }
            
            context.operationBuilder().extensions(extensions);
        } catch (Exception e) {
            log.debug("扩展字段设置失败: {}", e.getMessage());
        }
    }
    
    @Override
    public boolean supports(DocumentationType delimiter) {
        // 支持Swagger 2.0，如果有OAS 3.0也尝试支持
        if (DocumentationType.SWAGGER_2.equals(delimiter)) {
            return true;
        }
        
        // 尝试支持OAS 3.0（如果可用）
        try {
            return "OAS_30".equals(delimiter.getName());
        } catch (Exception e) {
            return false;
        }
    }
}