package cn.yunzhixue.ability.center.examsprint.infrastructure.report.rendering.achievement;

import org.junit.jupiter.api.Test;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import static org.assertj.core.api.Assertions.assertThat;

class AchievementExamSprintReportSvgChartBuilderTest {

    private static final Pattern SELF_CLOSING_RECT_PATTERN = Pattern.compile("<rect\\b[^>]*/>");

    @Test
    void comparisonBarChartKeepsTinyPositiveBarsProportionalToAxisScale() {
        AchievementExamSprintReportSvgChartBuilder builder = new AchievementExamSprintReportSvgChartBuilder();

        String svg = builder.comparisonBarChart(
                "vocabulary-growth-chart",
                "词汇量对比",
                "训练前",
                1,
                "1 词",
                "训练后",
                1000,
                "1000 词",
                "#448aff");

        String beforeBar = extractRect(svg, "chart-bar chart-bar-before");
        String afterBar = extractRect(svg, "chart-bar chart-bar-after");

        assertThat(beforeBar)
                .contains("height='0'")
                .contains("fill='#448aff'")
                .doesNotContain("fill='#9fb3c8'")
                .doesNotContain("height='18'");
        assertThat(afterBar)
                .contains("height='144'")
                .contains("fill='#448aff'");
    }

    @Test
    void comparisonBarChartDeclaresBatikCjkFontFamilyOnInlineSvg() {
        AchievementExamSprintReportSvgChartBuilder builder = new AchievementExamSprintReportSvgChartBuilder();

        String svg = builder.comparisonBarChart(
                "vocabulary-growth-chart",
                "词汇量对比",
                "训练前",
                2328,
                "2328 词",
                "训练后",
                2347,
                "2347 词",
                "#448aff");

        assertThat(svg).contains("<svg class='achievement-bar-chart vocabulary-growth-chart' font-family=\"'MiSans VF', MiSans, ReportFont, sans-serif\"");
    }

    private String extractRect(String svgOrHtml, String rectClass) {
        Matcher rectMatcher = SELF_CLOSING_RECT_PATTERN.matcher(svgOrHtml);
        String singleQuotedClass = "class='" + rectClass + "'";
        String doubleQuotedClass = "class=\"" + rectClass + "\"";
        while (rectMatcher.find()) {
            String rect = rectMatcher.group();
            if (rect.contains(singleQuotedClass) || rect.contains(doubleQuotedClass)) {
                return rect;
            }
        }
        throw new AssertionError("rect should exist for class '" + rectClass + "' in SVG/HTML fragment:\n" + svgOrHtml);
    }
}
