package com.pharmacopoeia.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pharmacopoeia.dto.ApiResponse;
import com.pharmacopoeia.exception.DashScopeRateLimitExceededException;
import com.pharmacopoeia.util.IpUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.resource.NoResourceFoundException;

import java.io.IOException;

@RestControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
    private static final ObjectMapper mapper = new ObjectMapper();
    private final HttpServletRequest request;

    public GlobalExceptionHandler(HttpServletRequest request) {
        this.request = request;
    }

    /** 静态资源 404：只记录来源 IP，不打印堆栈 */
    @ExceptionHandler(NoResourceFoundException.class)
    public void handleNoResource(NoResourceFoundException e, HttpServletResponse response) throws IOException {
        String ip = IpUtils.getClientIp(request);
        log.info("NoResourceFound from ip={}: path={}",
                ip, e.getResourcePath());
        writeJson(response, HttpStatus.NOT_FOUND, ApiResponse.error(404, "Resource not found"));
    }

    @ExceptionHandler(IllegalArgumentException.class)
    public void handleBadRequest(IllegalArgumentException e, HttpServletResponse response) throws IOException {
        writeJson(response, HttpStatus.BAD_REQUEST, ApiResponse.error(400, e.getMessage()));
    }

    /** 百炼 API 限流 → 503，告知前端服务暂时不可用 */
    @ExceptionHandler(DashScopeRateLimitExceededException.class)
    public void handleDashScopeRateLimit(DashScopeRateLimitExceededException e,
                                          HttpServletResponse response) throws IOException {
        log.warn("DashScope rate limit exceeded: {}", e.getMessage());
        writeJson(response, HttpStatus.SERVICE_UNAVAILABLE,
                ApiResponse.error(503, e.getMessage()));
    }

    @ExceptionHandler(RuntimeException.class)
    public void handleRuntime(RuntimeException e, HttpServletResponse response) throws IOException {
        log.error("Runtime error: {}", e.getMessage(), e);
        writeJson(response, HttpStatus.INTERNAL_SERVER_ERROR, ApiResponse.error(500, e.getMessage()));
    }

    @ExceptionHandler(Exception.class)
    public void handleGeneral(Exception e, HttpServletResponse response) throws IOException {
        log.error("Unexpected error: {}", e.getMessage(), e);
        writeJson(response, HttpStatus.INTERNAL_SERVER_ERROR, ApiResponse.error(500, "Internal server error"));
    }

    private void writeJson(HttpServletResponse response, HttpStatus status, ApiResponse<?> body) throws IOException {
        if (response.isCommitted()) {
            log.warn("Response already committed, cannot write error body");
            return;
        }
        response.setStatus(status.value());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.setCharacterEncoding("UTF-8");
        mapper.writeValue(response.getWriter(), body);
    }
}