package com.seer.teach.teacher.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;

@Slf4j
@Component
public class RateUtils {

    /**
     * 百分比字符串转正确率（"62%" -> 0.62）
     *
     * @param percent 百分比字符串
     * @return 正确率
     */
    public static BigDecimal percentStrToRate(String percent) {
        if (percent == null || percent.trim().isEmpty() || "0%".equals(percent)) {
            return BigDecimal.ZERO;
        }
        return new BigDecimal(percent.replace("%", ""))
                .divide(BigDecimal.valueOf(100), 4, RoundingMode.HALF_UP);
    }

    /**
     * 计算提升百分比
     *
     * @param current 当前正确率
     * @param history 历史正确率
     * @return 提升百分比
     */
    public static BigDecimal calculateImprovementPercent(BigDecimal current, BigDecimal history) {
        if (history.compareTo(BigDecimal.ZERO) <= 0) {
            // 历史为 0，认为是首次学习
            return BigDecimal.valueOf(100);
        }
        BigDecimal improve = current.subtract(history)
                .divide(history, 2, RoundingMode.HALF_UP)
                .multiply(BigDecimal.valueOf(100))
                .setScale(0, RoundingMode.HALF_UP);
        // 限制范围 [-100, 100]
        return improve.max(BigDecimal.valueOf(-100))
                .min(BigDecimal.valueOf(100));
    }
}
