"""Rich renderers for metabranch CLI output."""

from __future__ import annotations

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

from .models import MetabranchDefinition, StatusResult, WorkflowJournal


def render_branch_list(
    console: Console, definitions: list[MetabranchDefinition]
) -> None:
    """Render discovered metabranches as a table."""
    if not definitions:
        console.print("[yellow]No metabranches known locally.[/]")
        return

    table = Table(title="Metabranches")
    table.add_column("Name", style="cyan")
    table.add_column("Base", style="magenta")
    table.add_column("Contained Branches", style="green")

    for definition in definitions:
        branches = ", ".join(definition.branches) if definition.branches else "-"
        table.add_row(definition.name, definition.base_ref, branches)

    console.print(table)


def render_status(console: Console, status: StatusResult) -> None:
    """Render the current branch and workflow status."""
    if status.is_metabranch and status.metabranch is not None:
        summary = Table.grid(padding=(0, 2))
        summary.add_column(style="bold cyan")
        summary.add_column()
        summary.add_row("Current", status.branch_name)
        summary.add_row("Base", status.metabranch.base_ref)
        summary.add_row("Branches", str(len(status.metabranch.branches)))
        summary.add_row(
            "Contained",
            ", ".join(status.metabranch.branches) if status.metabranch.branches else "-",
        )
        summary.add_row("Local Active", status.local_active_metabranch or "-")
        summary.add_row("Tracking", status.tracking_branch or "-")
        summary.add_row("Ahead", _count_text(status.ahead))
        summary.add_row("Behind", _count_text(status.behind))
        summary.add_row("Remote Config", status.remote_config_created_at or "-")
        summary.add_row("Remote Config Updated", status.remote_config_updated_at or "-")
        summary.add_row("Remote Head Updated", status.remote_head_updated_at or "-")
        console.print(Panel(summary, title="Metabranch Status"))

        branches = Table(title="Contained Branches")
        branches.add_column("Branch", style="cyan", overflow="fold")
        branches.add_column("Availability", style="green")
        branches.add_column("On Meta", justify="center")
        branches.add_column("Not On Meta", justify="right")
        branches.add_column("Remote", style="magenta", overflow="fold")
        branches.add_column("R Ahead", justify="right")
        branches.add_column("R Behind", justify="right")
        for branch_state in status.branch_states:
            branches.add_row(
                branch_state.name,
                branch_state.state,
                _bool_text(branch_state.in_metabranch),
                _count_text(branch_state.not_in_metabranch),
                branch_state.tracking_branch or "-",
                _count_text(branch_state.ahead),
                _count_text(branch_state.behind),
            )
        if not status.branch_states:
            branches.add_row("-", "none", "-", "-", "-", "-", "-")
        console.print(branches)
    else:
        notice = status.notices[0] if status.notices else "Not on a metabranch."
        console.print(Panel(notice, title="Status"))

    if status.active_workflow is not None:
        render_workflow_summary(console, status.active_workflow)
    if status.repo_lock is not None:
        title = "Repo Lock"
        if status.repo_lock.is_stale:
            title = "Repo Lock (Stale)"
        lock_body = (
            f"Owner: {status.repo_lock.lock.owner}\n"
            f"Operation: {status.repo_lock.lock.operation or '-'}\n"
            f"Metabranch: {status.repo_lock.lock.metabranch_name or '-'}"
        )
        if status.repo_lock.reason is not None:
            lock_body = f"{lock_body}\nReason: {status.repo_lock.reason}"
        console.print(Panel(lock_body, title=title))


def _count_text(value: int | None) -> str:
    """Format ahead/behind counts for table display."""
    if value is None:
        return "-"
    return str(value)


def _bool_text(value: bool | None) -> str:
    """Format optional boolean values for table display."""
    if value is None:
        return "-"
    return "yes" if value else "no"


def render_workflow_summary(
    console: Console,
    journal: WorkflowJournal,
    *,
    verb: str | None = None,
) -> None:
    """Render a workflow journal summary."""
    title = "Workflow" if verb is None else f"{verb} Workflow"
    body = (
        f"Type: {journal.workflow_type}\n"
        f"Metabranch: {journal.metabranch_name}\n"
        f"Status: {journal.status}\n"
        f"Step: {journal.current_step}"
    )
    console.print(Panel(body, title=title))


def render_progress(console: Console, message: str) -> None:
    """Render one workflow progress line."""
    console.print(f"[cyan]>[/] {message}")
