package shop.alien.storeplatform.util;

import com.alibaba.fastjson2.JSONArray;
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.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;

import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

/**
 * 服务端文本内容审核（moderate-url）。无有效文本则直接通过；图/视频不参与，第二参请传 {@code null}。
 */
@Slf4j
@Component
@RefreshScope
@RequiredArgsConstructor
public class AiContentModerationUtil {

    private static final String RESULTS = "results";
    private static final String TEXT_INPUT_MARKER = "[TEXT INPUT]";
    private static final String GENERIC_FAILURE = "审核异常";

    private final RestTemplate restTemplate;

    @Value("${ai.service.moderate-url}")
    private String moderateUrl;

    public static class AuditResult {
        private final boolean passed;
        private final String failureReason;

        public AuditResult(boolean passed, String failureReason) {
            this.passed = passed;
            this.failureReason = failureReason;
        }

        public boolean isPassed() {
            return passed;
        }

        public String getFailureReason() {
            return failureReason;
        }
    }

    public AuditResult auditContent(String text, List<String> imageUrls) {
        if (imageUrls != null && !imageUrls.isEmpty()) {
            log.debug("auditContent: 忽略 imageUrls(size={})，请统一传 null", imageUrls.size());
        }
        if (!StringUtils.hasText(text)) {
            log.debug("auditContent: 无有效文本，跳过 moderate");
            return new AuditResult(true, null);
        }
        try {
            return requestModerate(text);
        } catch (Exception e) {
            log.error("auditContent 异常", e);
            return new AuditResult(false, GENERIC_FAILURE);
        }
    }

    private AuditResult requestModerate(String text) {
        try {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.MULTIPART_FORM_DATA);
            MultiValueMap<String, Object> body = new LinkedMultiValueMap<>();
            body.add("text", text);

            ResponseEntity<String> response =
                    restTemplate.postForEntity(moderateUrl, new HttpEntity<>(body, headers), String.class);

            if (response.getStatusCode() != HttpStatus.OK) {
                log.error("moderate HTTP 非 200: {}", response.getStatusCode());
                return new AuditResult(false, GENERIC_FAILURE);
            }
            String responseBody = response.getBody();
            if (!StringUtils.hasText(responseBody)) {
                log.error("moderate 响应体为空");
                return new AuditResult(false, GENERIC_FAILURE);
            }
            log.debug("moderate 响应: {}", responseBody);
            return parseModerateResponse(JSONObject.parseObject(responseBody));
        } catch (Exception e) {
            log.error("调用 moderate 失败", e);
            return new AuditResult(false, GENERIC_FAILURE);
        }
    }

    private AuditResult parseModerateResponse(JSONObject json) {
        try {
            JSONArray results = json.getJSONArray(RESULTS);
            if (results == null || results.isEmpty()) {
                log.warn("moderate 返回 results 为空");
                return new AuditResult(false, GENERIC_FAILURE);
            }

            Set<String> reasons = new LinkedHashSet<>();
            for (int i = 0; i < results.size(); i++) {
                JSONObject item = results.getJSONObject(i);
                if (item == null || !Boolean.TRUE.equals(item.getBoolean("flagged"))) {
                    continue;
                }
                reasons.add(flaggedItemReason(item.getString("filename")));
            }

            if (reasons.isEmpty()) {
                return new AuditResult(true, null);
            }
            String joined = String.join("; ", reasons);
            log.warn("moderate 命中违规: {}", joined);
            return new AuditResult(false, joined);
        } catch (Exception e) {
            log.error("解析 moderate 响应失败", e);
            return new AuditResult(false, GENERIC_FAILURE);
        }
    }

    private static String flaggedItemReason(String filename) {
        if (TEXT_INPUT_MARKER.equals(filename)) {
            return "含违规词汇";
        }
        if (StringUtils.hasText(filename) && filename.startsWith("http")) {
            return "图片内容违规";
        }
        return "内容违规";
    }
}
