package com.emoon.tongue.service.impl;

import com.emoon.tongue.domain.vo.TongueImageCheckVo;
import com.emoon.tongue.service.ITongueImageCheckService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.yaml.snakeyaml.Yaml;

import java.io.InputStream;
import java.util.List;
import java.util.Map;
import java.util.Random;

/**
 * 舌象图片校验服务实现类（Mock版本）
 *
 * @author destiny
 * @date 2025-12-11
 */
@Slf4j
@Service
public class TongueImageCheckServiceImpl implements ITongueImageCheckService {

    private final Random random = new Random();
    private List<Map<String, Object>> checkRules;

    public TongueImageCheckServiceImpl() {
        loadCheckRules();
    }

    /**
     * 加载校验规则
     */
    private void loadCheckRules() {
        try {
            Yaml yaml = new Yaml();
            InputStream inputStream = this.getClass().getClassLoader()
                    .getResourceAsStream("tongue-image-check-rules.yml");
            if (inputStream != null) {
                Map<String, Object> data = yaml.load(inputStream);
                this.checkRules = (List<Map<String, Object>>) data.get("tongueImageCheckRules");
                log.info("舌象图片校验规则加载成功，共{}条规则", this.checkRules.size());
            }
        } catch (Exception e) {
            log.error("加载舌象图片校验规则失败", e);
        }
    }

    @Override
    public TongueImageCheckVo checkTongueImage(String imageUrl) {
        log.info("开始校验舌象图片: {}", imageUrl);

        TongueImageCheckVo result = new TongueImageCheckVo();

        // Mock实现：80%概率通过，20%概率随机返回一个错误
        if (random.nextDouble() < 0.8) {
            // 通过校验
            result.setErrorCode(0);
            result.setErrorType("");
            result.setJudgeStandard("");
            result.setOptimizeSuggestion("");
            result.setPassed(true);
            log.info("舌象图片校验通过");
        } else {
            // 随机选择一个错误规则
            if (checkRules != null && !checkRules.isEmpty()) {
                Map<String, Object> randomRule = checkRules.get(random.nextInt(checkRules.size()));

                result.setErrorCode((Integer) randomRule.get("errorCode"));
                result.setErrorType((String) randomRule.get("errorType"));
                result.setJudgeStandard((String) randomRule.get("judgeStandard"));
                result.setOptimizeSuggestion((String) randomRule.get("optimizeSuggestion"));
                result.setPassed(false);

                log.info("舌象图片校验不通过，错误码: {}, 错误类型: {}",
                        result.getErrorCode(), result.getErrorType());
            } else {
                // 如果规则加载失败，默认通过
                result.setErrorCode(0);
                result.setPassed(true);
            }
        }

        return result;
    }
}