package com.flowable.devops.controller;

import com.flowable.devops.workflow.plugin.PluginDescriptor;
import com.flowable.devops.workflow.plugin.PluginManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 插件管理API
 * 
 * 提供插件的查询、启用/禁用等管理功能
 * 
 * @author Flowable Team
 * @since 1.0.0
 */
@Slf4j
@RestController
@RequestMapping("/api/plugins")
@CrossOrigin(origins = "*")
public class PluginController {
    
    @Autowired
    private PluginManager pluginManager;
    
    /**
     * 获取所有插件
     * 
     * GET /api/plugins
     * 
     * @return 插件列表
     */
    @GetMapping
    public ResponseEntity<List<PluginDescriptor>> getAllPlugins() {
        log.debug("查询所有插件");
        
        List<PluginDescriptor> plugins = pluginManager.getAllPlugins();
        
        log.debug("返回 {} 个插件", plugins.size());
        return ResponseEntity.ok(plugins);
    }
    
    /**
     * 获取已启用的插件
     * 
     * GET /api/plugins/enabled
     * 
     * @return 已启用的插件列表
     */
    @GetMapping("/enabled")
    public ResponseEntity<List<PluginDescriptor>> getEnabledPlugins() {
        log.debug("查询已启用的插件");
        
        List<PluginDescriptor> plugins = pluginManager.getEnabledPlugins();
        
        log.debug("返回 {} 个已启用插件", plugins.size());
        return ResponseEntity.ok(plugins);
    }
    
    /**
     * 获取单个插件详情
     * 
     * GET /api/plugins/{pluginId}
     * 
     * @param pluginId 插件ID
     * @return 插件详情
     */
    @GetMapping("/{pluginId}")
    public ResponseEntity<PluginDescriptor> getPlugin(@PathVariable String pluginId) {
        log.debug("查询插件: {}", pluginId);
        
        PluginDescriptor plugin = pluginManager.getPlugin(pluginId);
        
        if (plugin == null) {
            log.warn("插件不存在: {}", pluginId);
            return ResponseEntity.notFound().build();
        }
        
        return ResponseEntity.ok(plugin);
    }
    
    /**
     * 按分类获取插件
     * 
     * GET /api/plugins/category/{category}
     * 
     * @param category 分类（API, DATABASE, LOGIC, NOTIFICATION, TRANSFORM, OTHER）
     * @return 该分类下的插件列表
     */
    @GetMapping("/category/{category}")
    public ResponseEntity<List<PluginDescriptor>> getPluginsByCategory(
            @PathVariable String category) {
        log.debug("查询分类插件: {}", category);
        
        try {
            com.flowable.devops.entity.NodeType.NodeCategory nodeCategory = 
                com.flowable.devops.entity.NodeType.NodeCategory.valueOf(category.toUpperCase());
            
            List<PluginDescriptor> plugins = pluginManager.getPluginsByCategory(nodeCategory);
            
            log.debug("返回 {} 个 {} 分类插件", plugins.size(), category);
            return ResponseEntity.ok(plugins);
            
        } catch (IllegalArgumentException e) {
            log.warn("无效的分类: {}", category);
            return ResponseEntity.badRequest().build();
        }
    }
    
    /**
     * 启用插件
     * 
     * POST /api/plugins/{pluginId}/enable
     * 
     * @param pluginId 插件ID
     * @return 无内容
     */
    @PostMapping("/{pluginId}/enable")
    public ResponseEntity<Void> enablePlugin(@PathVariable String pluginId) {
        log.info("启用插件: {}", pluginId);
        
        try {
            pluginManager.enablePlugin(pluginId);
            log.info("插件已启用: {}", pluginId);
            return ResponseEntity.ok().build();
            
        } catch (IllegalArgumentException e) {
            log.warn("启用插件失败: {} - {}", pluginId, e.getMessage());
            return ResponseEntity.notFound().build();
            
        } catch (Exception e) {
            log.error("启用插件失败: {} - {}", pluginId, e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 禁用插件
     * 
     * POST /api/plugins/{pluginId}/disable
     * 
     * @param pluginId 插件ID
     * @return 无内容
     */
    @PostMapping("/{pluginId}/disable")
    public ResponseEntity<Void> disablePlugin(@PathVariable String pluginId) {
        log.info("禁用插件: {}", pluginId);
        
        try {
            pluginManager.disablePlugin(pluginId);
            log.info("插件已禁用: {}", pluginId);
            return ResponseEntity.ok().build();
            
        } catch (IllegalArgumentException e) {
            log.warn("禁用插件失败: {} - {}", pluginId, e.getMessage());
            return ResponseEntity.notFound().build();
            
        } catch (Exception e) {
            log.error("禁用插件失败: {} - {}", pluginId, e.getMessage(), e);
            return ResponseEntity.internalServerError().build();
        }
    }
    
    /**
     * 重新加载插件（热加载）
     * 
     * POST /api/plugins/{pluginId}/reload
     * 
     * 注意：第一期不支持热加载
     * 
     * @param pluginId 插件ID
     * @return 无内容
     */
    @PostMapping("/{pluginId}/reload")
    public ResponseEntity<Map<String, String>> reloadPlugin(@PathVariable String pluginId) {
        log.warn("尝试重新加载插件: {} (功能尚未实现)", pluginId);
        
        return ResponseEntity.status(501).body(
            Map.of(
                "error", "Not Implemented",
                "message", "热加载功能将在第二期实现，请重启应用以重新加载插件"
            )
        );
    }
    
    /**
     * 获取插件统计信息
     * 
     * GET /api/plugins/statistics
     * 
     * @return 统计信息
     */
    @GetMapping("/statistics")
    public ResponseEntity<Map<String, Object>> getStatistics() {
        log.debug("查询插件统计信息");
        
        Map<String, Object> stats = pluginManager.getStatistics();
        
        return ResponseEntity.ok(stats);
    }
    
    /**
     * 检查插件是否存在
     * 
     * HEAD /api/plugins/{pluginId}
     * 
     * @param pluginId 插件ID
     * @return 200 存在，404 不存在
     */
    @RequestMapping(value = "/{pluginId}", method = RequestMethod.HEAD)
    public ResponseEntity<Void> checkPluginExists(@PathVariable String pluginId) {
        boolean exists = pluginManager.hasPlugin(pluginId);
        
        if (exists) {
            return ResponseEntity.ok().build();
        } else {
            return ResponseEntity.notFound().build();
        }
    }
}
