package com.tzld.piaoquan.recommend.server.util;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * dk_elements JSON 串解析
 * value 形如 {"党的二十大":{"d":"事件","p":"主题","c":2.1},"民生":{"d":"事件","p":"主题","c":1.4}}
 *
 * 当前只需要 element kw 列表 (LinkedHashMap 保 JSON 出现顺序), 未来若要 c 加权再扩展
 * kw 清理跟 dk_keywords 老逻辑对齐: 去掉空白/制表/冒号
 */
@Slf4j
public class DkElementsUtils {

    public static List<String> parseElementKws(String dkElementsStr) {
        return parseElementKws(dkElementsStr, Double.NEGATIVE_INFINITY);
    }

    /**
     * 带贡献分阈值过滤: 只保留 element 内部 "c" 字段 >= minScore 的 kw, 按 JSON 出现顺序
     * c 缺失或不可解析的 element 也会被剔除 (不放过任何不达标的)
     */
    public static List<String> parseElementKws(String dkElementsStr, double minScore) {
        if (StringUtils.isBlank(dkElementsStr)) {
            return Collections.emptyList();
        }
        try {
            JSONObject obj = JSONObject.parseObject(dkElementsStr);
            if (obj == null || obj.isEmpty()) {
                return Collections.emptyList();
            }
            List<String> kws = new ArrayList<>(obj.size());
            for (String raw : obj.keySet()) {
                if (Double.isFinite(minScore) && !passContribFilter(obj, raw, minScore)) {
                    continue;
                }
                String kw = cleanKw(raw);
                if (!kw.isEmpty()) {
                    kws.add(kw);
                }
            }
            return kws;
        } catch (Exception e) {
            log.error("parseElementKws error, value=[{}]", dkElementsStr, e);
            return Collections.emptyList();
        }
    }

    private static boolean passContribFilter(JSONObject obj, String rawKey, double minScore) {
        try {
            JSONObject element = obj.getJSONObject(rawKey);
            if (element == null) {
                return false;
            }
            Double c = element.getDouble("c");
            return c != null && c >= minScore;
        } catch (Exception e) {
            return false;
        }
    }

    private static String cleanKw(String kw) {
        if (kw == null) {
            return "";
        }
        return kw.replaceAll("(\\s+|\\t|:)", "");
    }
}
