import re
import unittest
from pathlib import Path


ROOT = Path(__file__).resolve().parents[1]
MIGRATE_PY = ROOT / "migrate.py"
CALCULATORS_TS = ROOT / "hdyc-svelte" / "src" / "lib" / "data" / "calculators.ts"
HOMEPAGE_SVELTE = ROOT / "hdyc-svelte" / "src" / "routes" / "+page.svelte"


def _extract_category_keys_from_migrate() -> list[str]:
    text = MIGRATE_PY.read_text(encoding="utf-8")
    match = re.search(r"CATEGORY_KEYS\s*=\s*\[(.*?)\]", text, flags=re.S)
    if not match:
        raise AssertionError("Could not find CATEGORY_KEYS in migrate.py")
    block = match.group(1)
    return re.findall(r"'([a-z0-9-]+)'", block)


def _extract_category_keys_from_generated_ts() -> list[str]:
    text = CALCULATORS_TS.read_text(encoding="utf-8")
    match = re.search(r"export const categories:[\s\S]*?=\s*\{([\s\S]*?)\n\};", text)
    if not match:
        raise AssertionError("Could not find categories object in calculators.ts")
    block = match.group(1)
    return re.findall(r"^\s*'?(?P<key>[a-z0-9-]+)'?\s*:", block, flags=re.M)


def _validate_required_categories(category_keys: list[str]) -> None:
    if "fluids" not in category_keys:
        raise AssertionError("Missing 'fluids' category")
    if "magnetism" not in category_keys:
        raise AssertionError("Missing 'magnetism' category")
    if len(category_keys) < 20:
        raise AssertionError("Category count dropped below 20")


class HomepageCategoryRegressionTests(unittest.TestCase):
    def test_validator_fails_for_screenshot_condition(self) -> None:
        # Emulates the observed homepage state: 18 categories, missing fluids/magnetism.
        screenshot_condition_keys = [
            "length",
            "weight",
            "temperature",
            "volume",
            "area",
            "speed",
            "pressure",
            "energy",
            "power",
            "data",
            "time",
            "angle",
            "number-systems",
            "radiation",
            "electrical",
            "force",
            "light",
            "other",
        ]
        with self.assertRaises(AssertionError):
            _validate_required_categories(screenshot_condition_keys)

    def test_generated_categories_include_fluids_and_magnetism(self) -> None:
        migrate_keys = _extract_category_keys_from_migrate()
        generated_keys = _extract_category_keys_from_generated_ts()

        _validate_required_categories(migrate_keys)
        _validate_required_categories(generated_keys)

    def test_homepage_uses_canonical_categories_map(self) -> None:
        text = HOMEPAGE_SVELTE.read_text(encoding="utf-8")

        self.assertIn("import { categories, totalCalculators } from '$lib/data/stats';", text)
        self.assertIn("requiredCategoryFallbacks", text)
        self.assertIn("fluids: { label: 'Fluids', icon: '💧' }", text)
        self.assertIn("magnetism: { label: 'Magnetism', icon: '🧲' }", text)
        self.assertIn("Object.entries(homepageCategories)", text)
        self.assertIn("Object.keys(homepageCategories).length", text)
        self.assertNotIn("getCategoriesWithCounts", text)


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