"""Tests for system font utilities."""

from types import ModuleType
import importlib.util
import pathlib
import sys

import pytest


@pytest.fixture
def system_module():
    """Load the system utilities module without importing the addon __init__."""
    module_name = "src.utils.system"
    original = sys.modules.pop(module_name, None)

    spec = importlib.util.spec_from_file_location(
        module_name,
        pathlib.Path(__file__).resolve().parents[3] / "src" / "utils" / "system.py",
    )
    module = importlib.util.module_from_spec(spec)
    assert spec.loader is not None
    sys.modules[module_name] = module
    spec.loader.exec_module(module)
    try:
        yield module
    finally:
        if original is None:
            sys.modules.pop(module_name, None)
        else:
            sys.modules[module_name] = original


def test_find_default_truetype_font_skips_fonts_without_latin(monkeypatch, system_module):
    """Ensure selection skips fonts that produce unusable glyph metrics."""
    try:
        from PIL import ImageFont
    except ImportError:
        pytest.skip("Pillow not available in test environment")

    def fake_system():
        return "Darwin"

    monkeypatch.setattr(system_module.platform, "system", fake_system)

    def fake_exists(path):
        return path in {"/bad/font.ttf", "/good/font.ttf"}

    monkeypatch.setattr(system_module.os.path, "exists", fake_exists)

    monkeypatch.setattr(
        system_module,
        "get_system_fonts",
        lambda: {"Bad": "/bad/font.ttf", "Good": "/good/font.ttf"},
    )

    class FontStub:
        def __init__(self, path):
            self.path = path

        def getbbox(self, text):
            if self.path == "/bad/font.ttf":
                if text == "H":
                    return (0, 10, 40, 50)
                return (0, 0, 100, 200)
            if text == "H":
                return (0, 12, 36, 52)
            return (0, 20, 30, 48)

    def fake_truetype(path, size):
        return FontStub(path)

    monkeypatch.setattr(ImageFont, "truetype", fake_truetype)
    system_module._DEFAULT_FONT_CACHE = None

    selected = system_module.find_default_truetype_font()
    assert selected == "/good/font.ttf"
