"""Filter sessions by project, date, or session ID."""

from __future__ import annotations

from datetime import datetime

from cc_logger.types.session import SessionInfo


def filter_by_project(sessions: list[SessionInfo], project: str) -> list[SessionInfo]:
    """Filter sessions by project path (exact or substring match)."""
    return [
        s for s in sessions
        if s.project_path == project or project in s.project_path
    ]


def filter_by_date(sessions: list[SessionInfo], since: str) -> list[SessionInfo]:
    """Filter sessions modified on or after the given date (YYYY-MM-DD)."""
    since_dt = datetime.fromisoformat(since)
    results: list[SessionInfo] = []
    for s in sessions:
        if not s.modified:
            continue
        try:
            mod_dt = datetime.fromisoformat(s.modified.replace("Z", "+00:00"))
            if mod_dt >= since_dt.astimezone(mod_dt.tzinfo) if mod_dt.tzinfo else mod_dt >= since_dt:
                results.append(s)
        except ValueError:
            continue
    return results


def filter_by_session_id(sessions: list[SessionInfo], session_id: str) -> list[SessionInfo]:
    """Filter to a single session by exact or prefix UUID match."""
    # Try exact match first
    exact = [s for s in sessions if s.session_id == session_id]
    if exact:
        return exact
    # Fall back to prefix match
    return [s for s in sessions if s.session_id.startswith(session_id)]


def apply_filters(
    sessions: list[SessionInfo],
    project: str | None = None,
    since: str | None = None,
    session_id: str | None = None,
) -> list[SessionInfo]:
    """Apply all provided filters (AND logic)."""
    result = [s for s in sessions if s.message_count > 0]
    if session_id:
        result = filter_by_session_id(result, session_id)
    if project:
        result = filter_by_project(result, project)
    if since:
        result = filter_by_date(result, since)
    return result
