package shop.alien.store.util.ai;

import com.alibaba.fastjson2.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.http.*;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.HttpServerErrorException;
import org.springframework.web.client.RestTemplate;

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

/**
 * AI 图片封面颜色提取工具类
 *
 * @author system
 * @since 2025-01-XX
 */
@Slf4j
@Component
@RefreshScope
@RequiredArgsConstructor
public class AiImageColorExtractUtil {

    private final RestTemplate restTemplate;

    private final AiAuthTokenUtil aiAuthTokenUtil;

    @Value("${ai.service.image-color-extract-url}")
    private String extractColorUrl;

    /**
     * 提取图片封面颜色
     *
     * @param imageUrl 图片URL
     * @return 颜色码，如果提取失败返回null
     */
    public String extractCoverColor(String imageUrl) {
        if (!StringUtils.hasText(imageUrl)) {
            log.warn("图片URL为空，无法提取颜色");
            return null;
        }

        // 获取AI服务访问令牌
        String accessToken = aiAuthTokenUtil.getAccessToken();
        if (!StringUtils.hasText(accessToken)) {
            log.error("获取AI服务访问令牌失败，无法调用颜色提取接口");
            return null;
        }

        try {
            // 构建请求体
            Map<String, Object> requestBody = new HashMap<>();
            requestBody.put("image_url", imageUrl);

            // 构建请求头，添加Authorization
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + accessToken);

            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestBody, headers);

            log.info("调用AI颜色提取接口，图片URL: {}", imageUrl);
            ResponseEntity<String> response = restTemplate.postForEntity(extractColorUrl, request, String.class);

            if (response != null && response.getStatusCode() == HttpStatus.OK) {
                String responseBody = response.getBody();
                log.info("AI颜色提取接口响应: {}", responseBody);

                if (StringUtils.hasText(responseBody)) {
                    JSONObject jsonObject = JSONObject.parseObject(responseBody);
                    if (jsonObject != null) {
                        Integer code = jsonObject.getInteger("code");
                        if (code != null && code == 200) {
                            JSONObject data = jsonObject.getJSONObject("data");
                            if (data != null) {
                                String colorCode = data.getString("color_code");
                                log.info("成功提取图片颜色码: {}", colorCode);
                                return colorCode;
                            } else {
                                log.warn("AI接口返回数据为空");
                            }
                        } else {
                            String message = jsonObject.getString("message");
                            log.warn("AI接口返回错误，code: {}, message: {}", code, message);
                        }
                    }
                }
            } else {
                log.error("AI颜色提取接口调用失败，HTTP状态码: {}", 
                        response != null ? response.getStatusCode() : "null");
            }
        } catch (HttpClientErrorException e) {
            log.error("调用AI颜色提取接口失败，HTTP客户端错误，状态码: {}, 响应体: {}, 图片URL: {}", 
                    e.getStatusCode(), e.getResponseBodyAsString(), imageUrl, e);
        } catch (HttpServerErrorException e) {
            log.error("调用AI颜色提取接口失败，HTTP服务器错误，状态码: {}, 响应体: {}, 图片URL: {}", 
                    e.getStatusCode(), e.getResponseBodyAsString(), imageUrl, e);
        } catch (Exception e) {
            log.error("调用AI颜色提取接口异常，图片URL: {}", imageUrl, e);
        }

        return null;
    }
}

