"""Tests for font utilities."""
from paper2md.types import BBox, Span
from paper2md.utils.fonts import (
    build_font_hierarchy, is_math_font, char_to_latex, FontHierarchy,
)


def _make_span(text, font="NimbusRomNo9L-Regu", size=12.0, bold=False):
    flags = 16 if bold else 0
    return Span(text, font, size, flags, 0, BBox(0, 0, len(text) * 6, 12))


def test_build_hierarchy_body_detection():
    spans = [_make_span("x" * 100, size=12.0)] * 10
    spans += [_make_span("Title", size=20.0, bold=True)]
    spans += [_make_span("Heading", size=17.0, bold=True)]
    h = build_font_hierarchy(spans)
    assert h.body_size == 12.0
    assert h.title_size == 20.0


def test_heading_level():
    h = FontHierarchy(
        body_font="Font",
        body_size=12.0,
        title_size=20.0,
        heading_sizes=[17.0, 14.0],
    )
    assert h.heading_level(20.0, False) == 1  # title
    assert h.heading_level(17.0, True) == 2   # H2
    assert h.heading_level(14.0, True) == 3   # H3
    assert h.heading_level(12.0, False) == 0  # body


def test_heading_requires_bold():
    h = FontHierarchy(
        body_font="Font",
        body_size=12.0,
        title_size=20.0,
        heading_sizes=[17.0],
    )
    assert h.heading_level(17.0, False) == 0  # not bold = not a heading


def test_is_footnote():
    h = FontHierarchy(body_font="Font", body_size=12.0, footnote_size=10.0)
    assert h.is_footnote(10.0)
    assert not h.is_footnote(12.0)


def test_is_math_font():
    # Pure math fonts: always math
    assert is_math_font("CMMI10")
    assert is_math_font("CMSY10")
    assert is_math_font("CMEX10")
    assert not is_math_font("NimbusRomNo9L-Regu")
    # CM text fonts: math when body is non-CM (e.g., NimbusRom)
    assert is_math_font("CMR10", body_font="NimbusRomNo9L-Regu")
    assert is_math_font("CMBX12", body_font="NimbusRomNo9L-Regu")
    # CM text fonts: NOT math when body is also CM
    assert not is_math_font("CMR10", body_font="CMR10")
    assert not is_math_font("CMBX12", body_font="CMR10")
    assert not is_math_font("CMTI10", body_font="CMR9")


def test_char_to_latex():
    assert char_to_latex("\u03b1", "CMMI10") == "\\alpha "
    assert char_to_latex("\u03b2", "CMMI10") == "\\beta "
    assert char_to_latex("x", "CMMI10") == "x"
