package com.example.demo.service;

import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;

import kong.unirest.HttpResponse;
import kong.unirest.Unirest;
import kong.unirest.UnirestException;

/**
 * API响应处理器
 * 统一处理API调用和返回值解析
 */
@Component
public class ApiResponseHandler {

    private static final Logger logger = LoggerFactory.getLogger(ApiResponseHandler.class);
    private final ObjectMapper objectMapper;

    public ApiResponseHandler() {
        this.objectMapper = new ObjectMapper();
        // Unirest配置已移至 UnirestConfig 统一管理，避免重复配置警告
    }

    /**
     * 通用API调用方法
     * @param url API地址
     * @param apiKey API密钥
     * @param requestBody 请求体
     * @return 处理后的响应数据
     */
    public Map<String, Object> callApi(String url, String apiKey, Map<String, Object> requestBody) {
        try {
            logger.info("调用API: {}", url);
            logger.info("请求参数: {}", requestBody);
            
            HttpResponse<String> response = Unirest.post(url)
                .header("Content-Type", "application/json")
                .header("Authorization", "Bearer " + apiKey)
                .body(objectMapper.writeValueAsString(requestBody))
                .asString();

            return processResponse(response);
            
        } catch (UnirestException e) {
            logger.error("API调用异常: {}", e.getMessage(), e);
            throw new RuntimeException("API调用失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("API调用处理异常: {}", e.getMessage(), e);
            throw new RuntimeException("API调用处理失败: " + e.getMessage());
        }
    }

    /**
     * GET请求API调用
     * @param url API地址
     * @param apiKey API密钥
     * @return 处理后的响应数据
     */
    public Map<String, Object> callGetApi(String url, String apiKey) {
        try {
            logger.info("调用GET API: {}", url);
            
            HttpResponse<String> response = Unirest.get(url)
                .header("Authorization", "Bearer " + apiKey)
                .asString();

            return processResponse(response);
            
        } catch (UnirestException e) {
            logger.error("GET API调用异常: {}", e.getMessage(), e);
            throw new RuntimeException("GET API调用失败: " + e.getMessage());
        } catch (Exception e) {
            logger.error("GET API调用处理异常: {}", e.getMessage(), e);
            throw new RuntimeException("GET API调用处理失败: " + e.getMessage());
        }
    }

    /**
     * 处理API响应
     * @param response HTTP响应
     * @return 解析后的响应数据
     */
    private Map<String, Object> processResponse(HttpResponse<String> response) {
        try {
            logger.info("API响应状态: {}", response.getStatus());
            logger.info("API响应内容: {}", response.getBody());
            
            // 检查HTTP状态码
            if (response.getStatus() != 200) {
                logger.error("API调用失败，HTTP状态: {}", response.getStatus());
                throw new RuntimeException("API调用失败，HTTP状态: " + response.getStatus());
            }
            
            // 检查响应体
            if (response.getBody() == null || response.getBody().trim().isEmpty()) {
                logger.error("API响应体为空");
                throw new RuntimeException("API响应体为空");
            }
            
            // 解析JSON响应
            Map<String, Object> responseBody = objectMapper.readValue(response.getBody(), Map.class);
            
            // 检查业务状态码
            Integer code = (Integer) responseBody.get("code");
            if (code == null) {
                logger.warn("响应中没有code字段，直接返回响应体");
                return responseBody;
            }
            
            if (code == 200) {
                logger.info("API调用成功: {}", responseBody);
                return responseBody;
            } else {
                String message = (String) responseBody.get("message");
                logger.error("API调用失败，业务状态码: {}, 消息: {}", code, message);
                throw new RuntimeException("API调用失败: " + message);
            }
            
        } catch (Exception e) {
            logger.error("处理API响应异常: {}", e.getMessage(), e);
            throw new RuntimeException("处理API响应失败: " + e.getMessage());
        }
    }

    /**
     * 获取视频列表的专用方法
     * @param apiKey API密钥
     * @param baseUrl 基础URL
     * @return 视频列表数据
     */
    public Map<String, Object> getVideoList(String apiKey, String baseUrl) {
        String url = baseUrl + "/user/ai/tasks/";
        return callGetApi(url, apiKey);
    }

    /**
     * 获取任务状态的专用方法
     * @param taskId 任务ID
     * @param apiKey API密钥
     * @param baseUrl 基础URL
     * @return 任务状态数据
     */
    public Map<String, Object> getTaskStatus(String taskId, String apiKey, String baseUrl) {
        String url = baseUrl + "/v1/tasks/" + taskId + "/status";
        return callGetApi(url, apiKey);
    }

    /**
     * 创建响应包装器
     * @param success 是否成功
     * @param data 数据
     * @param message 消息
     * @return 包装后的响应
     */
    public Map<String, Object> createResponse(boolean success, Object data, String message) {
        Map<String, Object> response = new HashMap<>();
        response.put("success", success);
        response.put("data", data);
        response.put("message", message);
        response.put("timestamp", System.currentTimeMillis());
        return response;
    }

    /**
     * 创建成功响应
     * @param data 数据
     * @return 成功响应
     */
    public Map<String, Object> createSuccessResponse(Object data) {
        return createResponse(true, data, "操作成功");
    }

    /**
     * 创建失败响应
     * @param message 错误消息
     * @return 失败响应
     */
    public Map<String, Object> createErrorResponse(String message) {
        return createResponse(false, null, message);
    }
}
