"""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)

    def test_differs(self):
        assert _pattern("differs") == set(view.DIFFERS_CHOICES)


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


class TestTheStoryTellsTheTruthAboutARefusal:
    """Dubai's edge answers 403 to our declared identity, so no run exists after 22 Aug and the
    story read "nothing attempted for N days" while verification check 396 (11 Sep) said
    BLOCKED. The newest BLOCKED check wins when no run has started since (Stream L, LT8)."""

    def test_refused_since_wins_over_nothing_attempted(self):
        from datetime import UTC, datetime, timedelta
        from types import SimpleNamespace

        from app.services.collector_view import _story

        old = datetime.now(UTC) - timedelta(days=24)
        runs = [SimpleNamespace(status="ok", started_at=old)]
        assert _story(runs)["story"].startswith("nothing attempted for")
        blocked = old + timedelta(days=20)
        told = _story(runs, refused_since=blocked)
        assert told["story"] == f"refused since {blocked.date().isoformat()}"
        assert told["refused_since"] is not None
        # A run since the check speaks for itself.
        later = [SimpleNamespace(status="ok", started_at=blocked + timedelta(days=1))]
        assert _story(later, refused_since=blocked)["story"] != f"refused since {blocked.date().isoformat()}"
        assert _story([], refused_since=blocked)["story"] == f"refused since {blocked.date().isoformat()}"
