"""preview command — show a message in the terminal."""

import typer
from rich.panel import Panel

from cli_framework import get_context
from send_message.cli import app
from send_message.commands._helpers import resolve_tool_and_session, show_available_sessions
from send_message.context import SendMessageContext
from session_store import MessageSelector
from session_store.errors import MessageNotFoundError, SessionNotFoundError


@app.command()
def preview(
    ctx: typer.Context,
    target: str = typer.Argument(
        ...,
        help="Message target: latest, HEAD, HEAD~N, <number>, first, search:<text>",
    ),
    full: bool = typer.Option(False, "--full", "-f", help="Show full content without truncation"),
) -> None:
    """Preview a session message in the terminal."""
    app_ctx = get_context(ctx)
    assert isinstance(app_ctx, SendMessageContext)
    console = app_ctx.console

    tool, session_id, store = resolve_tool_and_session(ctx)

    try:
        session = store.get_session(session_id, tool=tool)
    except SessionNotFoundError:
        console.print(f"[red]Error:[/red] Session not found: {session_id}")
        show_available_sessions(console, store, tool=tool)
        raise typer.Exit(1) from None

    try:
        message = store.select_message(target, session_id=session_id, tool=tool)
    except MessageNotFoundError:
        console.print(f"[red]Error:[/red] Message not found for target: {target}")
        selector = MessageSelector()
        candidates = selector.filter_assistant(session.messages)
        if candidates:
            console.print(f"[dim]Available assistant messages ({len(candidates)}):[/dim]")
            for i, msg in enumerate(candidates[:10], 1):
                preview = msg.content[:60].replace("\n", " ")
                console.print(f"  {i}. {preview}")
        else:
            console.print("[dim]No assistant messages in this session.[/dim]")
        raise typer.Exit(1) from None

    header = (
        f"[bold]Tool:[/bold] {tool}  "
        f"[bold]Session:[/bold] {session_id}\n"
        f"[bold]Role:[/bold] {message.role}  "
        f"[bold]Created:[/bold] {message.created_at.isoformat()}"
    )

    if full:
        content = message.content
    else:
        console_height = console.size.height or 24
        max_lines = max(10, console_height - 10)
        lines = message.content.split("\n")
        if len(lines) > max_lines:
            content = (
                "\n".join(lines[:max_lines]) + f"\n\n[dim]... ({len(lines) - max_lines} more lines,"
                " use --full to see all)[/dim]"
            )
        else:
            content = message.content

    panel = Panel(content, title=header, border_style="blue")
    console.print(panel)
