package com.example.service;

import com.example.common.config.TokenUtils;
import com.example.common.enums.ResultCodeEnum;
import com.example.entity.Account;
import com.example.exception.CustomException;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class AIChatService {

    private static final Logger log = LoggerFactory.getLogger(AIChatService.class);

    @Resource
    private RestTemplate restTemplate;
    
    @Value("${dashscope.api-key}")
    private String apiKey;
    
    @Value("${dashscope.model}")
    private String model;
    
    private final String API_URL = "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
    
    /**
     * 发送消息到通义千问API并获取回复
     */
    public String sendMessage(String message) {
        // 获取当前登录用户
        Account currentUser = TokenUtils.getCurrentUser();
        if (currentUser == null) {
            throw new CustomException(ResultCodeEnum.TOKEN_CHECK_ERROR);
        }
        
        log.info("准备发送消息到通义千问API，用户ID: {}, 消息内容: {}", currentUser.getId(), message);
        
        // 构建请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        headers.set("Authorization", "Bearer " + apiKey);
        
        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("model", model);
        
        // 添加参数
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("temperature", 0.7);
        parameters.put("top_p", 0.8);
        parameters.put("result_format", "message");
        requestBody.put("parameters", parameters);
        
        // 添加用户消息
        Map<String, Object> input = new HashMap<>();
        List<Map<String, Object>> messages = new ArrayList<>();
        
        Map<String, Object> userMessage = new HashMap<>();
        userMessage.put("role", "user");
        userMessage.put("content", message);
        messages.add(userMessage);
        
        input.put("messages", messages);
        requestBody.put("input", input);
        
        try {
            // 记录完整请求
            log.info("发送请求到API: {}", API_URL);
            log.info("请求体: {}", requestBody);
            
            // 发送请求
            HttpEntity<Map<String, Object>> requestEntity = new HttpEntity<>(requestBody, headers);
            ResponseEntity<Map> response = restTemplate.exchange(API_URL, HttpMethod.POST, requestEntity, Map.class);
            
            // 记录响应
            log.info("API响应状态码: {}", response.getStatusCode());
            log.debug("API响应内容: {}", response.getBody());
            
            if (response.getStatusCode() == HttpStatus.OK) {
                Map<String, Object> responseBody = response.getBody();
                if (responseBody != null) {
                    // 检查错误字段
                    if (responseBody.containsKey("code") && !responseBody.get("code").equals(200) && responseBody.containsKey("message")) {
                        String errorMessage = (String) responseBody.get("message");
                        log.error("API返回错误: {}", errorMessage);
                        return "API错误: " + errorMessage;
                    }
                    
                    // 尝试多种可能的响应格式
                    String content = extractContentFromResponse(responseBody);
                    if (content != null) {
                        return content;
                    }
                }
                
                log.warn("无法从API响应中提取内容: {}", responseBody);
                return "抱歉，我无法理解您的问题。";
            } else {
                log.error("API响应错误状态码: {}", response.getStatusCode());
                throw new CustomException(ResultCodeEnum.SYSTEM_ERROR.code, "AI服务异常，请稍后再试");
            }
        } catch (Exception e) {
            log.error("调用通义千问API出错: ", e);
            throw new CustomException(ResultCodeEnum.SYSTEM_ERROR.code, "AI服务异常: " + e.getMessage());
        }
    }
    
    /**
     * 尝试从不同格式的响应中提取内容
     */
    private String extractContentFromResponse(Map<String, Object> responseBody) {
        // 格式1: output.choices[0].message.content
        try {
            if (responseBody.containsKey("output")) {
                Map<String, Object> output = (Map<String, Object>) responseBody.get("output");
                if (output.containsKey("choices")) {
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) output.get("choices");
                    if (choices != null && !choices.isEmpty()) {
                        Map<String, Object> choice = choices.get(0);
                        if (choice.containsKey("message")) {
                            Map<String, Object> message = (Map<String, Object>) choice.get("message");
                            if (message.containsKey("content")) {
                                return (String) message.get("content");
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.warn("尝试格式1提取内容失败: ", e);
        }
        
        // 格式2: data.choices[0].content
        try {
            if (responseBody.containsKey("data")) {
                Map<String, Object> data = (Map<String, Object>) responseBody.get("data");
                if (data.containsKey("choices")) {
                    List<Map<String, Object>> choices = (List<Map<String, Object>>) data.get("choices");
                    if (choices != null && !choices.isEmpty()) {
                        Map<String, Object> choice = choices.get(0);
                        if (choice.containsKey("content")) {
                            return (String) choice.get("content");
                        }
                    }
                }
            }
        } catch (Exception e) {
            log.warn("尝试格式2提取内容失败: ", e);
        }
        
        // 格式3: result
        try {
            if (responseBody.containsKey("result")) {
                return (String) responseBody.get("result");
            }
        } catch (Exception e) {
            log.warn("尝试格式3提取内容失败: ", e);
        }
        
        // 记录完整响应，便于调试
        log.info("响应体解析失败，完整响应: {}", responseBody);
        return null;
    }
} 