package com.emoon.tongue.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.emoon.tongue.config.TongueImageCheckProperties;
import com.emoon.tongue.domain.vo.TongueImageCheckVo;
import com.emoon.tongue.service.ITongueImageCheckService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Random;

/**
 * 舌象图片校验服务实现类（Mock版本）
 * 使用Spring Boot Configuration Properties管理校验规则配置
 *
 * @author destiny
 * @date 2025-12-11
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class TongueImageCheckServiceImpl implements ITongueImageCheckService {

    private final Random random = new Random();

    /**
     * 注入舌象图片检查规则配置
     */
    private final TongueImageCheckProperties tongueImageCheckProperties;

    @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 {
            // 随机选择一个错误规则
            List<TongueImageCheckProperties.CheckRule> rules = tongueImageCheckProperties.getRules();
            if (CollectionUtil.isNotEmpty(rules)) {
                TongueImageCheckProperties.CheckRule randomRule = rules.get(random.nextInt(rules.size()));

                result.setErrorCode(randomRule.getErrorCode());
                result.setErrorType(randomRule.getErrorType());
                result.setJudgeStandard(randomRule.getJudgeStandard());
                result.setOptimizeSuggestion(randomRule.getOptimizeSuggestion());
                result.setPassed(false);

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

        return result;
    }
}
