"""Colony console display — Rich-based visual output for terminal recording."""

from __future__ import annotations

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

from fliiq.runtime.colony.models import (
    ColonyState,
    GovernanceDecision,
    IntelBrief,
    Proposal,
    QAMetrics,
    Vote,
)

console = Console()

# Agent role → color mapping
AGENT_COLORS: dict[str, str] = {
    "intelligence": "cyan",
    "research": "magenta",
    "scout": "yellow",
    "qa": "green",
    "governance": "red",
    "orchestrator": "dim",
}


def print_experiment_header(
    state: ColonyState, elapsed_hours: float, duration: float,
) -> None:
    """Status panel shown at bootstrap and periodically."""
    content = (
        f"Branch: {state.branch_name}   "
        f"Status: {state.status}\n"
        f"Duration: {duration}h   "
        f"Elapsed: {elapsed_hours:.1f}h   "
        f"Cycles: {state.cycle_count}"
    )
    console.print(Panel(
        content,
        title=f"Colony Experiment {state.experiment_id:03d}",
        border_style="bold blue",
    ))


def print_agent_start(role: str, trigger: str) -> None:
    """Agent start banner with role and trigger."""
    color = AGENT_COLORS.get(role, "white")
    console.print()
    console.print(Rule(
        f" {role.title()} Agent ",
        style=color,
    ))
    console.print(f"  [dim]{trigger[:100]}[/dim]")


def print_agent_done(role: str, iterations: int) -> None:
    """Agent completion line."""
    color = AGENT_COLORS.get(role, "white")
    console.print(
        f"  [{color}]Completed[/{color}] in {iterations} iterations",
    )


def print_agent_error(role: str, error: str) -> None:
    """Agent failure line."""
    console.print(f"  [red]FAILED: {error}[/red]")


def print_new_brief(brief: IntelBrief) -> None:
    """Announce a new intelligence brief."""
    console.print()
    console.print(
        f"  [cyan]BRIEF:[/cyan] {brief.id} — "
        f"[bold]{brief.title}[/bold]",
    )
    console.print(
        f"    Source: {brief.source_type} | "
        f"Relevance: {brief.relevance}",
    )
    if brief.summary:
        console.print(f"    {brief.summary[:150]}")


def print_new_proposal(proposal: Proposal) -> None:
    """Announce a new proposal."""
    console.print()
    console.print(
        f"  [yellow]PROPOSAL:[/yellow] {proposal.id} — "
        f"[bold]{proposal.title}[/bold]",
    )
    console.print(
        f"    Type: {proposal.type} | Risk: {proposal.risk} | "
        f"Proposer: {proposal.proposer}",
    )


def print_new_vote(vote: Vote) -> None:
    """Announce a vote on a proposal."""
    color = "green" if vote.position.value == "support" else "red"
    if "conditions" in vote.position.value:
        color = "yellow"
    console.print()
    console.print(
        f"  [{color}]VOTE[/{color}] on {vote.proposal_id}: "
        f"[bold]{vote.position.value.upper()}[/bold]",
    )
    if vote.reasoning:
        console.print(f"    {vote.reasoning[:150]}")


def print_governance_decision(decision: GovernanceDecision) -> None:
    """Announce a governance decision."""
    outcome = decision.outcome.value.upper()
    color = "green" if "approved" in outcome.lower() else "red"
    if "revision" in outcome.lower() or "escalat" in outcome.lower():
        color = "yellow"
    console.print()
    console.print(
        f"  [{color}]DECISION[/{color}] on {decision.proposal_id}: "
        f"[bold {color}]{outcome}[/bold {color}]",
    )
    if decision.reasoning:
        console.print(f"    {decision.reasoning[:150]}")
    if decision.commit_sha:
        console.print(f"    Commit: {decision.commit_sha[:10]}")


def print_proposal_board(
    proposals: list[Proposal],
    votes_map: dict[str, int],
) -> None:
    """Show proposal status table."""
    if not proposals:
        return
    table = Table(title="Proposal Board", border_style="dim")
    table.add_column("ID", style="bold")
    table.add_column("Title")
    table.add_column("Status")
    table.add_column("Votes", justify="right")

    for p in proposals[-10:]:  # last 10
        status_color = {
            "approved": "green", "implemented": "green",
            "rejected": "red",
            "proposed": "yellow", "under_review": "yellow",
            "escalated": "magenta",
        }.get(p.status.value, "white")
        table.add_row(
            p.id,
            p.title[:30],
            f"[{status_color}]{p.status.value.upper()}[/{status_color}]",
            str(votes_map.get(p.id, 0)),
        )
    console.print()
    console.print(table)


def print_metrics_summary(metrics: QAMetrics) -> None:
    """Show QA metrics inline."""
    pass_style = "green" if metrics.fail_count == 0 else "red"
    console.print(
        f"  METRICS: {metrics.test_count} tests | "
        f"[{pass_style}]{metrics.pass_count} pass[/{pass_style}] | "
        f"{metrics.fail_count} fail | "
        f"{metrics.lint_issues} lint issues",
    )


def print_code_freeze(hour: float) -> None:
    """Code freeze announcement."""
    console.print()
    console.print(Panel(
        f"Code freeze activated at hour {hour:.1f}\n"
        "Only QA monitoring continues.",
        title="CODE FREEZE",
        border_style="bold yellow",
    ))


def print_shutdown_summary(state: ColonyState) -> None:
    """Final experiment summary panel."""
    content = (
        f"Cycles: {state.cycle_count}\n"
        f"Proposals: {state.proposals_total} total, "
        f"{state.proposals_approved} approved, "
        f"{state.proposals_rejected} rejected"
    )
    console.print()
    console.print(Panel(
        content,
        title=f"Colony Experiment {state.experiment_id:03d} Complete",
        border_style="bold green",
    ))
