package com.ssyf.third.trans.baidu;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestClientException;

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

/**
 * 百度翻译服务实现
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class BaiduTranslateService {
    
    @Autowired
    private final BaiduTranslateProperties properties;

    /**
     * 执行文本翻译
     *
     * @param query 待翻译文本
     * @param from  源语言代码（如：en）
     * @param to    目标语言代码（如：zh）
     * @return 翻译结果对象
     * @throws TranslateException 翻译业务异常
     */
    public BaiduTranslateResult translate(String query, String from, String to) {
        // 1. 构建请求参数
        Map<String, String> params = buildRequestParams(query, from, to);
        
        // 2. 发送API请求
        BaiduTranslateResult result;
        try {
            log.debug("Sending translation request: {}", params);

            String jsonString = HttpGet.get(properties.getApiUrl(), params);
            result = JSONUtil.toBean(jsonString, BaiduTranslateResult.class);
            
            log.debug("Received translation response: {}", result);
        } catch (RestClientException e) {
            log.error("Translation API request failed", e);
            throw new TranslateException("NETWORK_ERROR", "翻译服务通信异常: " + e.getMessage());
        }
        
        // 3. 处理API响应
        if (result == null) {
            log.error("Received empty translation response");
            throw new TranslateException("EMPTY_RESPONSE", "翻译服务返回空响应");
        }
        
        // 4. 错误处理
        if (result.getErrorCode() != null) {
            log.error("Translation failed with error: {} - {}", 
                     result.getErrorCode(), result.getErrorMsg());
            throw new TranslateException(result.getErrorCode(), 
                    "翻译服务错误: " + result.getErrorMsg());
        }
        
        // 5. 验证结果
        if (result.getTransResult() == null || result.getTransResult().isEmpty()) {
            log.warn("Translation returned empty result");
            throw new TranslateException("EMPTY_RESULT", "未获取到有效翻译结果");
        }
        
        return result;
    }

    /**
     * 构建请求参数（包含签名生成）
     */
    private Map<String, String> buildRequestParams(String query, String from, String to) {
        Map<String, String> params = new HashMap<>();
        
        // 基础参数
        params.put("q", query);
        params.put("from", from);
        params.put("to", to);
        params.put("appid", properties.getAppId());
        
        // 生成随机盐值
        String salt = String.valueOf(System.currentTimeMillis());
        params.put("salt", salt);
        
        // 生成签名：MD5(appid + q + salt + securityKey)
        String signStr = properties.getAppId() + query + salt + properties.getSecurityKey();
        String sign = MD5Util.md5Hex(signStr);
        params.put("sign", sign);
        
        return params;
    }
}