package com.it.rattan.monisuo.exception;

import com.it.rattan.monisuo.common.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.io.PrintWriter;
import java.io.StringWriter;

/**
 * 全局异常处理器
 */
@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理 NestedServletException (Spring MVC 包装的异常)
     */
    @ExceptionHandler(org.springframework.web.util.NestedServletException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleNestedServletException(org.springframework.web.util.NestedServletException e) {
        Throwable rootCause = getRootCause(e);
        
        // 如果根因是 StackOverflowError
        if (rootCause instanceof StackOverflowError) {
            StackOverflowError soe = (StackOverflowError) rootCause;
            StackTraceElement[] stack = soe.getStackTrace();
            StringBuilder sb = new StringBuilder("StackOverflowError at:\n");
            for (int i = 0; i < Math.min(30, stack.length); i++) {
                sb.append("  at ").append(stack[i]).append("\n");
            }
            log.error("StackOverflowError 发生 (via NestedServletException):\n{}", sb.toString());
            return Result.fail("系统错误：序列化循环引用，请联系管理员");
        }
        
        log.error("NestedServletException 发生: {}", e.getMessage());
        return Result.fail("系统异常: " + rootCause.getMessage());
    }
    
    /**
     * 获取异常的根因
     */
    private Throwable getRootCause(Throwable throwable) {
        Throwable cause = throwable;
        while (cause.getCause() != null && cause.getCause() != cause) {
            cause = cause.getCause();
        }
        return cause;
    }

    /**
     * 处理 StackOverflowError
     */
    @ExceptionHandler(StackOverflowError.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleStackOverflowError(StackOverflowError e) {
        // 打印前30行堆栈，避免递归
        StackTraceElement[] stack = e.getStackTrace();
        StringBuilder sb = new StringBuilder("StackOverflowError at:\n");
        for (int i = 0; i < Math.min(30, stack.length); i++) {
            sb.append("  at ").append(stack[i]).append("\n");
        }
        log.error("StackOverflowError 发生:\n{}", sb.toString());
        return Result.fail("系统错误：序列化循环引用，请联系管理员");
    }

    /**
     * 处理 OutOfMemoryError
     */
    @ExceptionHandler(OutOfMemoryError.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleOutOfMemoryError(OutOfMemoryError e) {
        log.error("OutOfMemoryError 发生", e);
        return Result.fail("系统错误：内存不足，请联系管理员");
    }

    /**
     * 处理运行时异常
     */
    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.BAD_REQUEST)
    public Result<Void> handleRuntimeException(RuntimeException e) {
        log.error("RuntimeException 发生", e);
        return Result.fail(e.getMessage());
    }

    /**
     * 处理所有其他异常
     */
    @ExceptionHandler(Exception.class)
    @ResponseBody
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public Result<Void> handleException(Exception e) {
        log.error("Exception 发生: {} - {}", e.getClass().getName(), e.getMessage());
        return Result.fail("系统异常: " + e.getMessage());
    }

    /**
     * 获取异常堆栈信息
     */
    private String getStackTrace(Throwable throwable) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        throwable.printStackTrace(pw);
        return sw.toString();
    }
}
