"""Shared helpers for send-message commands."""

from __future__ import annotations

import typer
from rich.console import Console
from rich.table import Table

from cli_framework import get_context
from send_message.context import SendMessageContext
from session_store import SessionStore
from session_store.errors import NoActiveSessionError


def get_store() -> SessionStore:
    """Get a SessionStore instance."""
    return SessionStore()


def resolve_tool_and_session(ctx: typer.Context) -> tuple[str, str, SessionStore]:
    """Resolve tool and session_id from context or auto-detection.

    Returns:
        Tuple of (tool, session_id, store).

    Raises:
        typer.Exit: If tool or session cannot be resolved, with error message.
    """
    app_ctx = get_context(ctx)
    assert isinstance(app_ctx, SendMessageContext)
    console = app_ctx.console
    store = get_store()

    tool = app_ctx.tool
    session_id = app_ctx.session_id

    if tool is None:
        try:
            tool = store.detect_tool()
        except NoActiveSessionError:
            console.print(
                "[red]Error:[/red] No active session detected. Specify --tool and --session-id."
            )
            raise typer.Exit(1) from None

    if session_id is None:
        session_id = store.detect_session(tool=tool)
        if session_id is None:
            console.print(
                f"[red]Error:[/red] No active session detected for tool '{tool}'. "
                "Specify --session-id."
            )
            raise typer.Exit(1) from None

    return tool, session_id, store


def show_available_sessions(console: Console, store: SessionStore, tool: str | None = None) -> None:
    """Print a table of available sessions to help the user pick one."""
    sessions = store.list_sessions(tool=tool, limit=10)
    if not sessions:
        console.print("[dim]No sessions available.[/dim]")
        return
    table = Table(title="Available sessions")
    table.add_column("Tool", style="cyan")
    table.add_column("Session ID", style="green")
    table.add_column("Title")
    table.add_column("Last Activity")
    for s in sessions:
        table.add_row(
            s.tool,
            s.session_id,
            s.title,
            s.last_activity.strftime("%Y-%m-%d %H:%M"),
        )
    console.print(table)
