"""Interactive questionary picker for sessions."""

from __future__ import annotations

from datetime import UTC

import questionary
from rich.console import Console

from session_store.models import SessionInfo


def _format_choice(session: SessionInfo) -> str:
    """Return a formatted choice string for questionary.

    Format:
      <session_id>  <last_activity_ago>  <title>
        <working_directory>
    """
    session_id = session.session_id
    ago = _format_last_activity(session.last_activity)
    title = (session.title or "")[:60]
    wdir = session.working_directory[:70]
    return f"{session_id:<20} {ago:<12} {title}\n    {wdir}"


def _format_last_activity(last_activity: object) -> str:
    """Return a human-readable relative time string.

    Expects a datetime. Falls back to a stringified value if not.
    """
    from datetime import datetime

    if not isinstance(last_activity, datetime):
        return str(last_activity)

    now = datetime.now(UTC)
    delta = now - last_activity
    total_seconds = int(delta.total_seconds())

    if total_seconds < 60:
        return "just now"
    if total_seconds < 3600:
        minutes = total_seconds // 60
        return f"{minutes}m ago"
    if total_seconds < 86400:
        hours = total_seconds // 3600
        return f"{hours}h ago"
    days = total_seconds // 86400
    if days < 30:
        return f"{days}d ago"
    return last_activity.strftime("%Y-%m-%d")


def pick_session(
    sessions: list[SessionInfo],
    *,
    console: Console | None = None,
) -> str | None:
    """Present an interactive questionary list and return the selected session ID.

    Returns None if the user cancels.
    """
    if not sessions:
        if console:
            console.print("[dim]No sessions found[/dim]")
        return None

    choices = [questionary.Choice(title=_format_choice(s), value=s.session_id) for s in sessions]

    try:
        result = questionary.select(
            "Choose a session to resume:",
            choices=choices,
            qmark="",
        ).ask()
    except KeyboardInterrupt:
        return None

    return result if isinstance(result, str) else None
