import re
import unittest
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
CALCULATORS_TS = ROOT / "hdyc-svelte" / "src" / "lib" / "data" / "calculators.ts"
CONVERSION_RATE_UTIL = ROOT / "hdyc-svelte" / "src" / "lib" / "utils" / "conversionRate.ts"
CATEGORY_PAGE = ROOT / "hdyc-svelte" / "src" / "routes" / "category" / "[category]" / "+page.svelte"
CALCULATOR_COMPONENT = ROOT / "hdyc-svelte" / "src" / "lib" / "components" / "Calculator.svelte"
TARGET_SLUG = "gauss-to-oersted"
NON_APPLICABLE_TWO_INPUT_STANDARD_SLUGS = {
    "grams-per-liter-to-molarity",
}


def _extract_calculator_block(slug: str) -> str:
    for line in CALCULATORS_TS.read_text(encoding="utf-8").splitlines():
        if f'"slug": "{slug}"' in line:
            return line
    raise AssertionError(f"Could not find calculator definition for '{slug}'")


class GaussToOerstedConversionRateRegressionTests(unittest.TestCase):
    def test_gauss_to_oersted_includes_factor_for_conversion_rate_and_tooltip(self) -> None:
        block = _extract_calculator_block(TARGET_SLUG)
        self.assertRegex(
            block,
            r'"factor":\s*[0-9.eE+-]+',
            "Missing factor on gauss-to-oersted prevents conversion rate text from rendering in both calculator footer and category tooltip.",
        )

    def test_conversion_rate_is_wired_to_both_surfaces(self) -> None:
        util_text = CONVERSION_RATE_UTIL.read_text(encoding="utf-8")
        category_page_text = CATEGORY_PAGE.read_text(encoding="utf-8")
        calculator_component_text = CALCULATOR_COMPONENT.read_text(encoding="utf-8")

        self.assertIn("getConversionRateText", util_text)
        self.assertIn("conversionRateText = getConversionRateText(calc)", category_page_text)
        self.assertIn('role="tooltip"', category_page_text)
        self.assertIn("conversionRateText = getConversionRateText(config)", calculator_component_text)
        self.assertIn('<span class="formula-hint">', calculator_component_text)

    def test_all_applicable_two_input_standard_calculators_have_factors(self) -> None:
        missing_factors: list[str] = []
        for line in CALCULATORS_TS.read_text(encoding="utf-8").splitlines():
            if '"type": "standard"' not in line:
                continue
            if '"labels": {"in1":' not in line or '"in2":' not in line or '"in3":' in line:
                continue
            slug_match = re.search(r'"slug": "([^"]+)"', line)
            if not slug_match:
                continue
            slug = slug_match.group(1)
            if slug in NON_APPLICABLE_TWO_INPUT_STANDARD_SLUGS:
                continue
            if '"factor":' not in line:
                missing_factors.append(slug)

        self.assertEqual(
            missing_factors,
            [],
            f"Two-input standard calculators missing factors (and therefore conversion-rate text): {missing_factors}",
        )


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