"""Shared ingest/STT lookback window helpers (0 = start of today)."""

from __future__ import annotations

from datetime import datetime, timedelta
from typing import List, Tuple


def lookback_floor_datetime(lookback_days: int, *, now: datetime | None = None) -> datetime:
    """Earliest call_starttime included in the lookback window."""
    current = (now or datetime.now()).replace(microsecond=0)
    if int(lookback_days) <= 0:
        return current.replace(hour=0, minute=0, second=0, microsecond=0)
    return current - timedelta(days=int(lookback_days))


def ingest_watermark_datetime(
    lookback_days: int,
    *,
    stored_watermark: datetime | None = None,
    db_max_start: datetime | None = None,
    now: datetime | None = None,
) -> datetime:
    """
    Resolve orchestrator ingest watermark.

    When lookback_days <= 0 (today only), ignore historical raw_calls rows
    before today so re-onboarded BIDs do not re-ingest older calls.
    """
    floor = lookback_floor_datetime(lookback_days, now=now)
    if int(lookback_days) <= 0:
        candidates = [
            d
            for d in (stored_watermark, db_max_start)
            if d is not None and d >= floor
        ]
        return max(candidates) if candidates else floor
    candidates = [d for d in (db_max_start, stored_watermark) if d is not None]
    return max(candidates) if candidates else floor


def sql_call_starttime_min_clause(
    lookback_days: int,
    column: str = "call_starttime",
) -> Tuple[str, List[int]]:
    """SQL fragment for call_starttime >= lookback window start."""
    col = str(column).strip() or "call_starttime"
    if int(lookback_days) <= 0:
        return f"{col} >= CURDATE()", []
    return f"{col} >= DATE_SUB(NOW(), INTERVAL %s DAY)", [int(lookback_days)]


def sql_stt_candidate_clause(
    lookback_days: int,
    column: str = "call_starttime",
    manual_flag_column: str = "selected_for_processing",
) -> Tuple[str, List[int]]:
    """
    STT queue eligibility: manual Call Sync / upload rows bypass lookback;
    auto-ingested rows must fall within the lookback window.
    """
    lookback_sql, lookback_params = sql_call_starttime_min_clause(lookback_days, column=column)
    flag_col = str(manual_flag_column).strip() or "selected_for_processing"
    return f"(COALESCE({flag_col}, 0) = 1 OR ({lookback_sql}))", lookback_params
