"""The review area's reading service: the parts that hold without a database.

The queries themselves are exercised against a real copy before deploy; what is pinned
here is what silently rots otherwise: the platform names a person reads, and the fact
that the route's accepted values and the service's own choices cannot drift apart.
"""

import re
from pathlib import Path

from app.services import collector_view as view
from app.services.collectors.registry import COLLECTORS

ROUTER = (Path(__file__).resolve().parents[1] / "app" / "routers" / "collectors.py").read_text()


def _pattern(name: str) -> set[str]:
    """The alternatives a route parameter accepts, read from its regex."""
    match = re.search(rf"{name}.*?pattern=\"\^\(([^)]+)\)\$\"", ROUTER, re.S)
    assert match, f"no pattern for {name}"
    return set(match.group(1).split("|"))


class TestPlatforms:
    def test_every_collector_resolves_to_a_named_platform(self):
        # An unnamed platform reads as "shopify_beauty" on the page: a module name leaking
        # into something a person is meant to understand.
        unknown = [slug for slug in COLLECTORS if view.platform_of(slug) in ("unknown", "")]
        assert not unknown, f"no platform name for {unknown}"

    def test_the_avolta_airports_share_one_platform(self):
        # One collector per platform is the design; ten airports reading as ten platforms
        # would hide that a fix at one is a fix at all.
        avolta = {view.platform_of(s) for s in COLLECTORS if s.startswith("avolta-")}
        assert len(avolta) == 1

    def test_an_unregistered_slug_is_not_invented(self):
        assert view.platform_of("no-such-collector") == "unknown"


class TestRouteAndServiceAgree:
    def test_missing_choices(self):
        assert _pattern("missing") == set(view.MISSING_CHOICES)

    def test_sorts(self):
        assert _pattern("sort") == set(view.SORTS)

    def test_groups(self):
        assert _pattern("group") == set(view.GROUPS)


class TestGrouping:
    def test_an_unknown_group_returns_nothing_rather_than_guessing(self):
        assert view.grouped(None, group="price") == {"group": "price", "rows": []}
