from __future__ import annotations

from typing import Iterable, Mapping, Protocol


class ConnLike(Protocol):
    def query(self, sql: str) -> Iterable[Mapping[str, str]]: ...

    def enqueue(self, task: str, payload: Mapping[str, str]) -> None: ...


def find_expired_evidence(conn: ConnLike) -> Iterable[Mapping[str, str]]:
    query = """
        SELECT DISTINCT entity_key, source
        FROM promotion_evidence
        WHERE expires_at IS NOT NULL
          AND expires_at < NOW()
    """
    return conn.query(query)


def requeue_refresh(conn: ConnLike, *, source: str, entity_key: str) -> None:
    payload = {"source": source, "entity_key": entity_key}
    conn.enqueue("connector.refresh", payload)


def run(conn: ConnLike) -> None:
    """Entry point for freshness maintenance job."""
    for row in find_expired_evidence(conn):
        requeue_refresh(conn, source=row["source"], entity_key=row["entity_key"])
