"""nestdx log — display session details."""

from __future__ import annotations

from pathlib import Path

import click
from rich.table import Table

from nestdx.config.parser import load_config
from nestdx.session.manager import SessionManager, SessionNotFoundError
from nestdx.utils.console import (
    STATUS_COLORS,
    console,
    format_duration,
    make_file_changes_table,
    make_tool_runs_table,
    make_violations_panel,
)


def _format_cost(cost: float) -> str:
    """Format a cost value as $X.XX or '-' if zero."""
    if cost > 0:
        return f"${cost:.2f}"
    return "-"


def _format_tokens(tokens: int) -> str:
    """Format a token count with comma separators or '-' if zero."""
    if tokens > 0:
        return f"{tokens:,}"
    return "-"


def _make_cost_table(session) -> Table | None:
    """Build a Rich table of token usage breakdown."""
    if not session.token_usage:
        return None

    table = Table(show_header=True, header_style="bold", box=None, pad_edge=False)
    table.add_column("Tool")
    table.add_column("Model")
    table.add_column("Input", justify="right")
    table.add_column("Output", justify="right")
    table.add_column("Total", justify="right")
    table.add_column("Cost", justify="right")

    for tu in session.token_usage:
        table.add_row(
            tu.tool,
            tu.model,
            _format_tokens(tu.input_tokens),
            _format_tokens(tu.output_tokens),
            _format_tokens(tu.total_tokens),
            _format_cost(tu.estimated_cost_usd),
        )

    return table


@click.command()
@click.option("--session", "-s", "session_id", default=None, help="Session ID (defaults to last completed).")
@click.option("--diff", "show_diff", is_flag=True, help="Show file changes.")
@click.option("--cost", "show_cost", is_flag=True, help="Show cost/token breakdown only.")
def log_cmd(session_id: str | None, show_diff: bool, show_cost: bool):
    """Display details of a session."""
    project_root = Path.cwd()

    try:
        config = load_config()
    except Exception as e:
        console.print(f"[red]Error:[/red] {e}")
        raise SystemExit(1)

    manager = SessionManager(config, project_root)

    if session_id:
        try:
            session = manager.get_session(session_id)
        except SessionNotFoundError as e:
            console.print(f"[red]Error:[/red] {e}")
            raise SystemExit(1)
    else:
        sessions = manager.list_sessions(limit=1)
        if not sessions:
            console.print("[yellow]No sessions found.[/yellow]")
            return
        session = sessions[0]

    # Cost-only view
    if show_cost:
        console.print(f"[bold]Session:[/bold] {session.id}")
        if session.token_usage:
            console.print("\n[bold]Token Usage & Cost:[/bold]")
            cost_table = _make_cost_table(session)
            if cost_table:
                console.print(cost_table)
            console.print(f"\n  [bold]Total tokens:[/bold] {_format_tokens(session.total_tokens)}")
            console.print(f"  [bold]Total cost:[/bold]   {_format_cost(session.total_cost)}")
        else:
            console.print("\n[yellow]No token/cost data recorded.[/yellow]")
        return

    # Session info
    status_color = STATUS_COLORS.get(session.status.value, "white")
    console.print(f"[bold]Session:[/bold] {session.id}")
    console.print(f"  Status: [{status_color}]{session.status.value}[/{status_color}]")
    console.print(f"  Started: {session.start_time:%Y-%m-%d %H:%M:%S UTC}")
    if session.end_time:
        console.print(f"  Ended:   {session.end_time:%Y-%m-%d %H:%M:%S UTC}")
    console.print(f"  Duration: {format_duration(session.duration_seconds)}")

    # Git snapshot
    if session.git_snapshot:
        gs = session.git_snapshot
        console.print("\n[bold]Git Snapshot:[/bold]")
        console.print(f"  Branch: {gs.branch}")
        console.print(f"  HEAD: {gs.head_sha[:8]}")
        if gs.dirty_files:
            console.print(f"  Dirty files: {len(gs.dirty_files)}")

    # Tool runs
    if session.tool_runs:
        console.print(f"\n[bold]Tool Runs ({len(session.tool_runs)}):[/bold]")
        console.print(make_tool_runs_table(session.tool_runs))

    # Token usage and cost
    if session.token_usage:
        console.print("\n[bold]Token Usage & Cost:[/bold]")
        cost_table = _make_cost_table(session)
        if cost_table:
            console.print(cost_table)
        console.print(f"\n  [bold]Total tokens:[/bold] {_format_tokens(session.total_tokens)}")
        console.print(f"  [bold]Total cost:[/bold]   {_format_cost(session.total_cost)}")

    # File changes
    if session.file_changes:
        console.print(f"\n[bold]File Changes ({len(session.file_changes)}):[/bold]")
        if show_diff or len(session.file_changes) <= 20:
            console.print(make_file_changes_table(session.file_changes))
        else:
            console.print(f"  {len(session.file_changes)} files changed. Use --diff to see details.")

    # Violations
    if session.violations:
        panel = make_violations_panel(session.violations)
        if panel:
            console.print()
            console.print(panel)
    else:
        console.print("\n[green]No violations.[/green]")
