package com.gxwebsoft.common.core.controller;

import com.gxwebsoft.common.core.web.ApiResult;
import com.gxwebsoft.common.core.web.BaseController;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 日志分析控制器
 * 
 * @author WebSoft
 * @since 2025-01-20
 */
@Slf4j
@RestController
@RequestMapping("/api/log-analysis")
@Tag(name = "日志分析", description = "日志分析和诊断接口")
public class LogAnalysisController extends BaseController {

    @Operation(summary = "分析系统日志")
    @GetMapping("/analyze")
    @PreAuthorize("hasAuthority('system:log:view')")
    public ApiResult<Map<String, Object>> analyzeSystemLogs(
            @Parameter(description = "查询的小时数，默认24小时") @RequestParam(defaultValue = "24") int hours,
            @Parameter(description = "日志级别过滤，如ERROR,WARN") @RequestParam(required = false) String level) {
        
        try {
            Map<String, Object> analysis = new HashMap<>();
            
            // 分析错误日志
            List<Map<String, Object>> errorLogs = analyzeErrorLogs(hours);
            analysis.put("errorLogs", errorLogs);
            
            // 分析安全事件
            List<Map<String, Object>> securityEvents = analyzeSecurityEvents(hours);
            analysis.put("securityEvents", securityEvents);
            
            // 分析性能问题
            List<Map<String, Object>> performanceIssues = analyzePerformanceIssues(hours);
            analysis.put("performanceIssues", performanceIssues);
            
            // 统计信息
            Map<String, Integer> statistics = getLogStatistics(hours);
            analysis.put("statistics", statistics);
            
            // 建议
            List<String> recommendations = generateRecommendations(errorLogs, securityEvents, performanceIssues);
            analysis.put("recommendations", recommendations);
            
            return success("日志分析完成", analysis);
            
        } catch (Exception e) {
            log.error("分析系统日志失败", e);
            return new ApiResult<>(1, "分析日志失败: " + e.getMessage());
        }
    }

    @Operation(summary = "获取实时日志")
    @GetMapping("/real-time")
    @PreAuthorize("hasAuthority('system:log:view')")
    public ApiResult<List<String>> getRealTimeLogs(
            @Parameter(description = "获取的行数") @RequestParam(defaultValue = "100") int lines) {
        
        try {
            List<String> recentLogs = getRecentLogLines(lines);
            return success("获取实时日志成功", recentLogs);
            
        } catch (Exception e) {
            log.error("获取实时日志失败", e);
            return new ApiResult<>(1, "获取实时日志失败: " + e.getMessage());
        }
    }

    @Operation(summary = "搜索日志")
    @GetMapping("/search")
    @PreAuthorize("hasAuthority('system:log:view')")
    public ApiResult<List<Map<String, Object>>> searchLogs(
            @Parameter(description = "搜索关键词") @RequestParam String keyword,
            @Parameter(description = "开始时间 yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) String startTime,
            @Parameter(description = "结束时间 yyyy-MM-dd HH:mm:ss") @RequestParam(required = false) String endTime) {
        
        try {
            List<Map<String, Object>> searchResults = searchLogsByKeyword(keyword, startTime, endTime);
            return success("搜索日志成功", searchResults);
            
        } catch (Exception e) {
            log.error("搜索日志失败", e);
            return new ApiResult<>(1, "搜索日志失败: " + e.getMessage());
        }
    }

    @Operation(summary = "清理旧日志")
    @PostMapping("/cleanup")
    @PreAuthorize("hasAuthority('system:log:delete')")
    public ApiResult<Map<String, Object>> cleanupOldLogs(
            @Parameter(description = "保留天数") @RequestParam(defaultValue = "30") int keepDays) {
        
        try {
            Map<String, Object> result = performLogCleanup(keepDays);
            return success("日志清理完成", result);
            
        } catch (Exception e) {
            log.error("清理日志失败", e);
            return new ApiResult<>(1, "清理日志失败: " + e.getMessage());
        }
    }

    /**
     * 分析错误日志
     */
    private List<Map<String, Object>> analyzeErrorLogs(int hours) {
        List<Map<String, Object>> errorLogs = new ArrayList<>();
        // 这里实现错误日志分析逻辑
        // 可以读取日志文件，解析ERROR级别的日志
        return errorLogs;
    }

    /**
     * 分析安全事件
     */
    private List<Map<String, Object>> analyzeSecurityEvents(int hours) {
        List<Map<String, Object>> securityEvents = new ArrayList<>();
        // 这里实现安全事件分析逻辑
        // 可以检查登录失败、权限拒绝等安全相关事件
        return securityEvents;
    }

    /**
     * 分析性能问题
     */
    private List<Map<String, Object>> analyzePerformanceIssues(int hours) {
        List<Map<String, Object>> performanceIssues = new ArrayList<>();
        // 这里实现性能问题分析逻辑
        // 可以检查慢查询、长时间处理的请求等
        return performanceIssues;
    }

    /**
     * 获取日志统计信息
     */
    private Map<String, Integer> getLogStatistics(int hours) {
        Map<String, Integer> statistics = new HashMap<>();
        statistics.put("totalLogs", 0);
        statistics.put("errorCount", 0);
        statistics.put("warnCount", 0);
        statistics.put("infoCount", 0);
        // 这里实现统计逻辑
        return statistics;
    }

    /**
     * 生成建议
     */
    private List<String> generateRecommendations(List<Map<String, Object>> errorLogs, 
                                               List<Map<String, Object>> securityEvents,
                                               List<Map<String, Object>> performanceIssues) {
        List<String> recommendations = new ArrayList<>();
        
        if (!errorLogs.isEmpty()) {
            recommendations.add("检测到错误日志，建议检查系统异常情况");
        }
        
        if (!securityEvents.isEmpty()) {
            recommendations.add("检测到安全事件，建议加强安全监控");
        }
        
        if (!performanceIssues.isEmpty()) {
            recommendations.add("检测到性能问题，建议优化系统性能");
        }
        
        if (recommendations.isEmpty()) {
            recommendations.add("系统运行正常，无异常发现");
        }
        
        return recommendations;
    }

    /**
     * 获取最近的日志行
     */
    private List<String> getRecentLogLines(int lines) throws IOException {
        List<String> recentLogs = new ArrayList<>();
        File logFile = new File("logs/websoft-core.log");
        
        if (logFile.exists()) {
            try (BufferedReader reader = new BufferedReader(new FileReader(logFile))) {
                String line;
                LinkedList<String> buffer = new LinkedList<>();
                
                while ((line = reader.readLine()) != null) {
                    buffer.add(line);
                    if (buffer.size() > lines) {
                        buffer.removeFirst();
                    }
                }
                
                recentLogs.addAll(buffer);
            }
        }
        
        return recentLogs;
    }

    /**
     * 根据关键词搜索日志
     */
    private List<Map<String, Object>> searchLogsByKeyword(String keyword, String startTime, String endTime) {
        List<Map<String, Object>> results = new ArrayList<>();
        // 这里实现关键词搜索逻辑
        return results;
    }

    /**
     * 执行日志清理
     */
    private Map<String, Object> performLogCleanup(int keepDays) {
        Map<String, Object> result = new HashMap<>();
        result.put("cleaned", false);
        result.put("message", "日志清理功能待实现");
        // 这里实现日志清理逻辑
        return result;
    }
}