"""Rich-based display helpers for ORBIT reports."""

from __future__ import annotations

from rich.console import Console

console = Console()


def print_header(title: str) -> None:
    """Print a report header with ═ underline."""
    console.print(f"\n[bold cyan]{title}[/bold cyan]")
    console.print("[cyan]" + "═" * len(title) + "[/cyan]")


def print_section(name: str) -> None:
    """Print a section name."""
    console.print(f"\n[bold yellow]{name}[/bold yellow]")


def print_metric(name: str, value: str, status: str = "ok") -> None:
    """Print a metric with status indicator.

    Args:
        name: Metric name.
        value: Display value.
        status: "ok" (green ✓), "warn" (yellow ⚠), or "bad" (red ✗).
    """
    if status == "ok":
        icon = "[green]\u2713[/green]"
    elif status == "warn":
        icon = "[yellow]\u26a0[/yellow]"
    else:
        icon = "[red]\u2717[/red]"
    console.print(f"  {icon} {name}: [bold]{value}[/bold]")


def format_duration(seconds: float) -> str:
    """Format seconds into a human-readable duration string."""
    if seconds < 60:
        return f"{seconds:.1f} sec"
    if seconds < 3600:
        return f"{seconds / 60:.1f} min"
    return f"{seconds / 3600:.1f} hours"


def progress_bar(score: float, width: int = 25, label: str = "") -> str:
    """Create an ASCII progress bar string.

    Args:
        score: Value between 0.0 and 1.0.
        width: Bar width in characters.
        label: Optional label to show after the bar.
    """
    score = max(0.0, min(1.0, score))
    filled = int(score * width)
    bar = "\u2593" * filled + "\u2591" * (width - filled)
    pct = f"{score * 100:.0f}%"
    if label:
        return f"{bar} {pct} {label}"
    return f"{bar} {pct}"


def sparkline(values: list[float], width: int = 20) -> str:
    """Create a sparkline string from a list of values.

    Args:
        values: Numeric values to plot.
        width: Maximum number of characters.
    """
    if not values:
        return ""
    blocks = " \u2581\u2582\u2583\u2584\u2585\u2586\u2587\u2588"
    mn, mx = min(values), max(values)
    rng = mx - mn if mx != mn else 1.0

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

    return "".join(
        blocks[min(len(blocks) - 1, int((v - mn) / rng * (len(blocks) - 1)))]
        for v in sampled
    )


def radar_chart(dimensions: dict[str, float], width: int = 40) -> str:
    """Create a simple horizontal radar/bar chart for quality dimensions.

    Args:
        dimensions: Dict of dimension_name -> score (0.0-1.0).
        width: Bar width.
    """
    lines = []
    max_label = max(len(k) for k in dimensions) if dimensions else 0
    for name, score in dimensions.items():
        score = max(0.0, min(1.0, score))
        filled = int(score * width)
        bar = "\u2588" * filled + "\u2591" * (width - filled)
        color = "green" if score >= 0.7 else "yellow" if score >= 0.4 else "red"
        lines.append(f"  {name:>{max_label}} [{color}]{bar}[/{color}] {score:.0%}")
    return "\n".join(lines)


def print_plugin_results(results: list) -> None:
    """Print results from custom analyzer plugins."""
    if not results:
        return
    print_section("Custom Analyzers")
    for r in results:
        print_metric(r.name, f"{r.score:.0%} \u2014 {r.summary}", r.status)
        if r.details:
            for k, v in r.details.items():
                console.print(f"      [dim]{k}: {v}[/dim]")
