"""Pricing a known handful of products ranks only their own observations.

The home page's featured savings priced their eight cards through
`list_products(only_ids=...)`, whose latest-observation subquery ranked every price
observation in the catalogue: about 450 of the request's 600 ms on staging (11 Sep),
six seconds for some airport sets, and growing with every collection. Scoped to the
products' listings, 130 to 220 ms with identical results. This pins the scoping.
"""

from sqlalchemy import select
from sqlalchemy.dialects import postgresql

from app.services import catalog_queries


def _sql(clause) -> str:
    return str(clause.compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}))


def test_a_known_handful_ranks_only_its_own_listings():
    sql = _sql(select(catalog_queries._latest_observation_subquery([52, 820])))
    assert "row_number() OVER (PARTITION BY price_observations.listing_id" in sql
    assert "price_observations.listing_id IN (SELECT listings.id" in sql
    assert "listings.product_id IN (52, 820)" in sql


def test_a_browse_still_ranks_the_catalogue():
    sql = _sql(select(catalog_queries._latest_observation_subquery()))
    assert "listings.product_id IN" not in sql


def test_list_products_passes_its_ids_to_the_ranking():
    base = catalog_queries._summary_base(None, None, product_ids=[7])
    assert "listings.product_id IN (7)" in _sql(base)
    assert "listings.product_id IN" not in _sql(catalog_queries._summary_base(None, None))


def test_a_route_ranks_only_its_products_at_its_shops():
    """The savings page (services/trip.py): a two-airport route took 0.7 to 2.3 s on
    staging (11 Sep) ranking the catalogue, and the planner re-ran the route's
    candidate query once per price row; now candidates are fetched once and the
    ranking covers only them at the route's shops, 1 to 80 ms, identical output."""
    sql = _sql(select(catalog_queries._latest_observation_subquery(product_ids=[5, 6], location_ids=[8, 13])))
    assert "listings.product_id IN (5, 6)" in sql
    assert "listings.location_id IN (8, 13)" in sql
