from __future__ import annotations

from datetime import datetime, timezone
from typing import Any

from niannian.chat.remember_gate import remember_gate
from niannian.chat.session import Turn


def _parse_created_at(iso: str) -> datetime:
    created = datetime.fromisoformat(iso)
    if created.tzinfo is None:
        created = created.replace(tzinfo=timezone.utc)
    return created


def _age_seconds(latest_iso: str, now: datetime) -> float:
    return (now - _parse_created_at(latest_iso)).total_seconds()


def is_memory_eligible_turn_pair(
    user_turn: Turn,
    assistant_turn: Turn,
    *,
    now: datetime | None = None,
    config: dict[str, Any] | None = None,
    for_batch: bool = False,
) -> bool:
    """Unified eligibility filter for remember / consolidate / history."""
    if user_turn.meta.get("recalled_at") or assistant_turn.meta.get("recalled_at"):
        return False
    if user_turn.meta.get("ingested_atom_id") or assistant_turn.meta.get("ingested_atom_id"):
        return False

    now = now or datetime.now(timezone.utc)
    chat_cfg = (config or {}).get("chat") or {}
    consolidation = chat_cfg.get("consolidation") or {}
    recall_window = float(chat_cfg.get("recall_window_seconds", 120))
    min_age = recall_window
    if for_batch:
        min_age += float(consolidation.get("grace_after_recall_seconds", 60))

    latest = max(user_turn.created_at, assistant_turn.created_at)
    if _age_seconds(latest, now) < min_age:
        return False

    if remember_gate(
        user_turn,
        assistant_turn,
        config=config,
        now=now,
        check_recall_window=False,
    ):
        return False

    return True
