"""Legibilidade dos temas usados pelo modelador e seus comandos."""

from pathlib import Path
import re
import unittest


STYLES = Path(__file__).resolve().parents[1] / "app" / "static" / "styles.css"


def luminance(color: str) -> float:
    channels = [int(color[index:index + 2], 16) / 255 for index in (1, 3, 5)]
    linear = [value / 12.92 if value <= 0.04045 else ((value + 0.055) / 1.055) ** 2.4
              for value in channels]
    return sum(value * weight for value, weight in zip(linear, (0.2126, 0.7152, 0.0722)))


def contrast(foreground: str, background: str) -> float:
    values = sorted((luminance(foreground), luminance(background)))
    return (values[1] + 0.05) / (values[0] + 0.05)


class ModelerVisualContractsTests(unittest.TestCase):
    def test_all_modeler_themes_keep_text_and_controls_readable(self) -> None:
        styles = STYLES.read_text(encoding="utf-8")

        def tokens(selector: str) -> dict[str, str]:
            block = re.search(r"^" + re.escape(selector) + r"\s*\{([^}]+)\}", styles, re.M)
            self.assertIsNotNone(block, selector)
            return dict(re.findall(r"(--window-[\w-]+):\s*(#[0-9a-fA-F]{6});", block[1]))

        defaults = tokens("body")
        surfaces = (
            "--window-surface", "--window-header-surface", "--window-inset-surface",
            "--window-action-surface", "--window-control-surface", "--window-control-hover",
        )
        for theme in ("standard", "metal", "graphite", "drawing-board"):
            palette = defaults | (tokens(f'body[data-interface-theme="{theme}"]')
                                  if theme != "standard" else {})
            for surface in surfaces:
                for text in ("--window-text", "--window-muted", "--window-accent"):
                    with self.subTest(theme=theme, text=text, surface=surface):
                        self.assertGreaterEqual(contrast(palette[text], palette[surface]), 4.5)
            with self.subTest(theme=theme, control="primary"):
                self.assertGreaterEqual(
                    contrast(palette["--window-accent-text"], palette["--window-accent"]), 4.5,
                )
            for status in ("--window-warning", "--window-danger"):
                with self.subTest(theme=theme, status=status):
                    self.assertGreaterEqual(
                        contrast(palette[status], palette["--window-inset-surface"]), 4.5,
                    )


if __name__ == "__main__":
    unittest.main()
