"""Rich display components for the AgentScout CLI."""

from __future__ import annotations

from rich.panel import Panel
from rich.table import Table


def thought_panel(thought: str, step_number: int) -> Panel:
    """Display an agent thought."""
    return Panel(
        thought,
        title=f"[bold cyan]Thought #{step_number}[/bold cyan]",
        border_style="cyan",
        padding=(0, 1),
    )


def action_panel(tool_name: str, tool_input: dict | None = None) -> Panel:
    """Display an agent action (tool call)."""
    content = f"[bold]{tool_name}[/bold]"
    if tool_input:
        args = ", ".join(f"{k}={v!r}" for k, v in tool_input.items())
        content += f"\n[dim]{args}[/dim]"
    return Panel(
        content,
        title="[bold yellow]Action[/bold yellow]",
        border_style="yellow",
        padding=(0, 1),
    )


def observation_panel(observation: str, max_length: int = 500) -> Panel:
    """Display an observation (tool result)."""
    display = observation[:max_length]
    if len(observation) > max_length:
        display += f"\n[dim]... ({len(observation) - max_length} chars truncated)[/dim]"
    return Panel(
        display,
        title="[bold green]Observation[/bold green]",
        border_style="green",
        padding=(0, 1),
    )


def finish_panel(message: str) -> Panel:
    """Display the final result."""
    return Panel(
        message,
        title="[bold green]Result[/bold green]",
        border_style="bold green",
        padding=(1, 2),
    )


def error_panel(error: str) -> Panel:
    """Display an error."""
    return Panel(
        f"[red]{error}[/red]",
        title="[bold red]Error[/bold red]",
        border_style="red",
        padding=(0, 1),
    )


def cost_display(
    input_tokens: int,
    output_tokens: int,
    cost_usd: float,
    budget_remaining: float | None = None,
) -> Panel:
    """Display cost information."""
    lines = [
        f"Tokens: [cyan]{input_tokens:,}[/cyan] in / [cyan]{output_tokens:,}[/cyan] out",
        f"Cost: [bold]${cost_usd:.4f}[/bold]",
    ]
    if budget_remaining is not None:
        color = "green" if budget_remaining > 0.5 else "yellow" if budget_remaining > 0.1 else "red"
        lines.append(f"Budget remaining: [{color}]${budget_remaining:.2f}[/{color}]")
    return Panel(
        "\n".join(lines),
        title="[bold]Cost[/bold]",
        border_style="dim",
        padding=(0, 1),
    )


def comparison_table(
    title: str,
    columns: list[str],
    rows: list[list[str]],
    highlight_col: int | None = None,
    highlight_row: int | None = 0,
) -> Table:
    """Build a comparison table with optional row highlighting."""
    table = Table(title=title, show_lines=True)

    for i, col in enumerate(columns):
        style = "bold cyan" if i == highlight_col else ""
        table.add_column(col, style=style)

    for i, row in enumerate(rows):
        style = "bold green" if i == highlight_row else ""
        table.add_row(*row, style=style)

    return table


def task_progress(
    step_count: int,
    max_steps: int,
    current_action: str = "",
) -> Panel:
    """Display task progress."""
    pct = min(100, int((step_count / max_steps) * 100)) if max_steps > 0 else 0
    bar_filled = pct // 5
    bar_empty = 20 - bar_filled
    bar = f"[green]{'=' * bar_filled}[/green][dim]{'.' * bar_empty}[/dim]"

    lines = [
        f"Step {step_count}/{max_steps} [{bar}] {pct}%",
    ]
    if current_action:
        lines.append(f"[dim]{current_action}[/dim]")

    return Panel(
        "\n".join(lines),
        title="[bold]Progress[/bold]",
        border_style="blue",
        padding=(0, 1),
    )


def sparkline(values: list[float], width: int = 20) -> str:
    """Generate a simple text-based sparkline from values."""
    if not values:
        return ""

    blocks = " ▁▂▃▄▅▆▇█"
    mn, mx = min(values), max(values)
    rng = mx - mn if mx != mn else 1

    # Sample values to fit width
    if len(values) > width:
        step = len(values) / width
        sampled = [values[int(i * step)] for i in range(width)]
    else:
        sampled = values

    chars = []
    for v in sampled:
        idx = int(((v - mn) / rng) * (len(blocks) - 1))
        chars.append(blocks[idx])
    return "".join(chars)


def price_trend_display(
    item_name: str,
    prices: list[float],
    currency: str = "USD",
) -> Panel:
    """Display a price trend with sparkline."""
    if not prices:
        return Panel(f"No price data for '{item_name}'", border_style="dim")

    chart = sparkline(prices)
    current = prices[-1]
    mn = min(prices)
    mx = max(prices)

    lines = [
        f"[bold]{item_name}[/bold]",
        f"Current: {currency} {current:.2f}",
        f"Range: {currency} {mn:.2f} - {currency} {mx:.2f}",
        f"Trend: {chart}",
    ]
    return Panel(
        "\n".join(lines),
        border_style="cyan",
        padding=(0, 1),
    )
