"""
PyArrow dataset filter expressions: legacy integer range + tuple-filter merge helpers.

Kept separate from :mod:`snapparquet.readers` to keep read orchestration thin.
"""

from __future__ import annotations

from typing import Any, List, Optional

import pyarrow.dataset as ds

from snapparquet.schema import column_is_integer_type, norm_col


def integer_range_expression(
    parquet_path: str,
    columns: Optional[List[str]],
    *,
    use_pushdown: bool,
    filter_column: Optional[str],
    range_start: Optional[int],
    range_end: Optional[int],
) -> Any:
    """
    Build ``(field >= lo) & (field <= hi)`` when pushdown is allowed and the column
    is integer-typed in the Parquet footer.

    Returns ``None`` if range pushdown does not apply.
    """
    lo = int(range_start) if range_start is not None else None
    hi = int(range_end) if range_end is not None else None
    range_ok = lo is not None and hi is not None and filter_column is not None
    fc = norm_col(filter_column) if filter_column else None

    if not (
        bool(use_pushdown)
        and range_ok
        and fc is not None
        and (columns is None or fc in columns)
        and column_is_integer_type(parquet_path, fc)
    ):
        return None
    try:
        fld = ds.field(fc)
        return (fld >= lo) & (fld <= hi)
    except Exception:
        return None


def merge_dataset_expressions(a: Any, b: Any) -> Any:
    """AND-merge two optional dataset filter expressions."""
    if a is not None and b is not None:
        return a & b
    return a if b is None else b
