"""Citation history filtering for the ``alice cite history`` subcommand.

Provides a pure filtering function following the ``filter_entries`` pattern
from ``alice_cli.commands.recall``, scoped to cite session types.
"""

from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from alice_cli.models import IndexEntry

_CITE_SESSION_TYPES = ("cite-process", "cite-lookup")


def filter_cite_entries(
    entries: list[IndexEntry],
    *,
    since: str | None = None,
    until: str | None = None,
    keyword: str | None = None,
    limit: int = 20,
) -> list[IndexEntry]:
    """Filter, sort, and limit index entries to cite sessions only.

    Pre-filters to entries with type in ``_CITE_SESSION_TYPES``, then applies
    date range, keyword, sort (timestamp descending), and limit.
    All filters are applied conjunctively (AND).
    """
    # ── Type filter: only cite sessions ───────────────────────────────
    result = [e for e in entries if e.type in _CITE_SESSION_TYPES]

    # ── Date filters ──────────────────────────────────────────────────
    if since is not None:
        result = [e for e in result if e.timestamp[:10] >= since]

    if until is not None:
        result = [e for e in result if e.timestamp[:10] <= until]

    # ── Keyword filter (case-insensitive on prompt_preview) ───────────
    if keyword is not None:
        kw_lower = keyword.lower()
        result = [e for e in result if kw_lower in e.prompt_preview.lower()]

    # ── Sort by timestamp descending ──────────────────────────────────
    result.sort(key=lambda e: e.timestamp, reverse=True)

    # ── Apply limit ───────────────────────────────────────────────────
    if limit > 0:
        result = result[:limit]

    return result
