package com.spider.quartz.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import okhttp3.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class BaiduAiTranslationService {

    @Value("${baidu.ai.api-key}")
    private String apiKey;

    @Value("${baidu.ai.secret-key}")
    private String secretKey;

    @Autowired
    private TranslationCacheService cacheService;

    private final OkHttpClient httpClient;
    private final ObjectMapper objectMapper;

    // 缓存Access Token（有效期为30天）
    private String cachedAccessToken;
    private long tokenExpireTime = 0;

    public BaiduAiTranslationService() {
        this.httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS)
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(10, TimeUnit.SECONDS)
                .build();
        this.objectMapper = new ObjectMapper();
    }

    /**
     * 主要翻译方法
     */
    public String translateWithCache(String text, String from, String to) {
        if (text == null || text.trim().isEmpty()) {
            return text;
        }

        // 1. 检查缓存
        String cachedResult = cacheService.get(text, from, to);
        if (cachedResult != null) {
            log.debug("缓存命中: [{}] -> [{}]", text, cachedResult);
            return cachedResult;
        }

        log.debug("缓存未命中，开始翻译: {}", text);

        // 2. 调用翻译API
        String translatedText;
        try {
            translatedText = callBaiduAiApi(text, from, to);
        } catch (Exception e) {
            log.error("翻译失败，返回原文。原文: {}, 错误: {}", text, e.getMessage());
            return text;
        }

        // 3. 缓存结果
        if (translatedText != null && !translatedText.equals(text)) {
            cacheService.set(text, from, to, translatedText);
            log.debug("翻译结果已缓存: [{}] -> [{}]", text, translatedText);
        }

        return translatedText;
    }

    /**
     * 调用百度AI平台翻译API
     */
    private String callBaiduAiApi(String text, String from, String to) throws Exception {
        // 获取Access Token
        String accessToken = getAccessToken();

        // 构建请求体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("from", from);
        requestBody.put("to", to);
        requestBody.put("q", text);

        String jsonBody = objectMapper.writeValueAsString(requestBody);

        RequestBody body = RequestBody.create(
                MediaType.parse("application/json; charset=utf-8"),
                jsonBody
        );

        // 构建请求
        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/rpc/2.0/mt/texttrans/v1?access_token=" + accessToken)
                .post(body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();

        // 执行请求
        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new RuntimeException("HTTP请求失败: " + response.code());
            }

            String responseBody = response.body().string();
            log.debug("API响应: {}", responseBody);

            // 解析响应
            Map<String, Object> result = objectMapper.readValue(responseBody, Map.class);

            // 检查错误
            if (result.containsKey("error_code")) {
                String errorCode = String.valueOf(result.get("error_code"));
                String errorMsg = String.valueOf(result.get("error_msg"));
                throw new RuntimeException("翻译API错误[" + errorCode + "]: " + errorMsg);
            }

            // 提取翻译结果
            Map<String, Object> resultData = (Map<String, Object>) result.get("result");
            if (resultData != null) {
                java.util.List<Map<String, String>> transResult =
                        (java.util.List<Map<String, String>>) resultData.get("trans_result");
                if (transResult != null && !transResult.isEmpty()) {
                    return transResult.get(0).get("dst");
                }
            }

            throw new RuntimeException("无法解析API响应");
        }
    }

    /**
     * 获取Access Token
     */
    private String getAccessToken() throws Exception {
        // 检查token是否有效
        if (cachedAccessToken != null && System.currentTimeMillis() < tokenExpireTime - 300000) {
            return cachedAccessToken;
        }

        // 对API Key和Secret Key进行URL编码
        String encodedApiKey = URLEncoder.encode(apiKey, "UTF-8");
        String encodedSecretKey = URLEncoder.encode(secretKey, "UTF-8");

        log.debug("原始API Key: {}", apiKey);
        log.debug("URL编码后API Key: {}", encodedApiKey);
        log.debug("原始Secret Key: {}...", secretKey.substring(0, Math.min(10, secretKey.length())));
        log.debug("URL编码后Secret Key: {}...", encodedSecretKey.substring(0, Math.min(20, encodedSecretKey.length())));

        // 构建token请求
        String requestBody = String.format(
                "grant_type=client_credentials&client_id=%s&client_secret=%s",
                encodedApiKey,
                encodedSecretKey
        );

        RequestBody body = RequestBody.create(
                MediaType.parse("application/x-www-form-urlencoded; charset=utf-8"),
                requestBody
        );

        Request request = new Request.Builder()
                .url("https://aip.baidubce.com/oauth/2.0/token")
                .post(body)
                .addHeader("Content-Type", "application/x-www-form-urlencoded")
                .build();

        // 获取token
        try (Response response = httpClient.newCall(request).execute()) {
            String responseBody = response.body().string();
            log.debug("Access Token响应: {}", responseBody);

            if (!response.isSuccessful()) {
                throw new RuntimeException("获取Access Token失败: " + response.code() + ", 响应: " + responseBody);
            }

            Map<String, Object> result = objectMapper.readValue(responseBody, Map.class);

            if (result.containsKey("error")) {
                String errorDescription = String.valueOf(result.get("error_description"));
                throw new RuntimeException("认证失败: " + result.get("error") + " - " + errorDescription);
            }

            cachedAccessToken = (String) result.get("access_token");
            long expiresIn = Long.parseLong(String.valueOf(result.get("expires_in"))) * 1000;
            tokenExpireTime = System.currentTimeMillis() + expiresIn;

            log.info("获取到新的Access Token，有效期: {}秒", expiresIn / 1000);
            return cachedAccessToken;
        }
    }

    /**
     * 便捷方法：英文到日文翻译
     */
    public String translateEnToJp(String text) {
        return translateWithCache(text, "en", "jp");
    }

    /**
     * 便捷方法：英文到中文翻译
     */
    public String translateEnToZh(String text) {
        return translateWithCache(text, "en", "zh");
    }
}