"""Rich console helpers — shared formatting for all CLI commands."""

from __future__ import annotations

import click
from rich.console import Console
from rich.panel import Panel
from rich.table import Table

console = Console()
err_console = Console(stderr=True)


def is_quiet() -> bool:
    """Return True if --quiet was passed to the CLI group."""
    ctx = click.get_current_context(silent=True)
    if ctx and ctx.obj:
        return ctx.obj.get("quiet", False)
    return False

CHANGE_COLORS = {
    "added": "green",
    "deleted": "red",
    "modified": "yellow",
    "renamed": "cyan",
}

STATUS_COLORS = {
    "active": "cyan",
    "completed": "green",
    "aborted": "red",
}


def format_duration(seconds: float | None) -> str:
    """Format seconds into 'Xm Ys' string."""
    if seconds is None:
        return "-"
    mins = int(seconds // 60)
    secs = int(seconds % 60)
    if mins > 0:
        return f"{mins}m {secs}s"
    return f"{secs}s"


def print_violations(violations: list, *, show_header: bool = True) -> None:
    """Print violations with Rich formatting."""
    if not violations:
        if show_header:
            console.print("  Violations: [green]none[/green]")
        return

    errors = [v for v in violations if v.severity == "error"]
    warnings = [v for v in violations if v.severity == "warning"]

    if show_header:
        console.print(
            f"  Violations: [red]{len(errors)} errors[/red], "
            f"[yellow]{len(warnings)} warnings[/yellow]"
        )

    for v in violations:
        color = "red" if v.severity == "error" else "yellow"
        loc = ""
        if v.file:
            loc = f" in {v.file}"
            if v.line:
                loc += f":{v.line}"
        console.print(f"    [{color}]{v.severity:>7}[/{color}]{loc}: {v.message}")


def make_file_changes_table(file_changes: list) -> Table:
    """Build a Rich table of file changes."""
    table = Table(show_header=True, header_style="bold", box=None, pad_edge=False)
    table.add_column("Type", style="bold", width=10)
    table.add_column("Path")
    table.add_column("+", justify="right", width=6)
    table.add_column("-", justify="right", width=6)

    for fc in file_changes:
        color = CHANGE_COLORS.get(fc.change_type, "white")
        table.add_row(
            f"[{color}]{fc.change_type}[/{color}]",
            fc.path,
            str(fc.additions) if fc.additions else "",
            str(fc.deletions) if fc.deletions else "",
        )
    return table


def make_tool_runs_table(tool_runs: list) -> Table:
    """Build a Rich table of tool runs."""
    table = Table(show_header=True, header_style="bold", box=None, pad_edge=False)
    table.add_column("Tool")
    table.add_column("Command")
    table.add_column("Duration", justify="right")
    table.add_column("Exit", justify="right", width=5)

    for tr in tool_runs:
        duration = ""
        if tr.end_time and tr.start_time:
            secs = (tr.end_time - tr.start_time).total_seconds()
            duration = format_duration(secs)
        exit_style = "green" if tr.exit_code == 0 else "red"
        exit_str = str(tr.exit_code) if tr.exit_code is not None else "-"
        table.add_row(
            tr.tool,
            tr.command,
            duration,
            f"[{exit_style}]{exit_str}[/{exit_style}]",
        )
    return table


def make_violations_panel(violations: list) -> Panel | None:
    """Build a Rich panel for violations, or None if clean."""
    if not violations:
        return None

    errors = [v for v in violations if v.severity == "error"]
    warnings = [v for v in violations if v.severity == "warning"]

    lines: list[str] = []
    for v in violations:
        color = "red" if v.severity == "error" else "yellow"
        loc = ""
        if v.file:
            loc = f" {v.file}"
            if v.line:
                loc += f":{v.line}"
        lines.append(f"[{color}]{v.severity:>7}[/{color}]{loc}: {v.message}")

    title = f"[red]{len(errors)} errors[/red], [yellow]{len(warnings)} warnings[/yellow]"
    return Panel("\n".join(lines), title=title, border_style="red" if errors else "yellow")
