"""Lifecycle panels: startup, agent, and exit panels for the CLI console."""

from __future__ import annotations

from datetime import datetime

from rich.panel import Panel

from yera.agents.registry import get_agent_metadata, get_agent_name
from yera.events.models import (
    ExitEventData,
    FailureExitEventData,
    SuccessExitEventData,
)


def startup_panel(
    start_time: datetime, top_level_agent_name: str | None = None
) -> Panel:
    """Cyan panel with run start time and top-level agent name."""
    formatted = start_time.strftime("%Y-%m-%d %H:%M:%S")
    lines = [f"Started: {formatted}"]
    if top_level_agent_name:
        lines.append(f"Top-level Agent: {top_level_agent_name}")
    return Panel(
        "\n".join(lines),
        title="Startup",
        border_style="cyan",
    )


def agent_panel(agent_id: str) -> Panel:
    """Yellow panel showing the active agent name and identifier."""
    name = get_agent_name(agent_id) or agent_id.split(".")[-1]
    meta = get_agent_metadata(agent_id)
    identifier = meta.identifier if meta is not None else agent_id
    body = f"Identifier:  {identifier}"

    return Panel(
        body,
        title=name,
        border_style="yellow",
    )


def exit_panel(
    exit_data: ExitEventData,
    run_time_seconds: float,
    failing_agent_name: str | None,
) -> Panel:
    """Cyan (success) or red (failure) panel with exit code, reason, return value, run time."""
    match exit_data:
        case SuccessExitEventData():
            border_style = "cyan"
            lines = [
                "Completed successfully",
                "",
                f"Exit code:    {exit_data.exit_code}",
                f"Reason:       {exit_data.reason or '—'}",
                f"Return value: {exit_data.return_value if exit_data.return_value is not None else 'None'}",
                "",
                f"Run time: {run_time_seconds:.2f} s",
            ]
        case FailureExitEventData():
            border_style = "red"
            lines = [
                "Exited with error",
                "",
                f"Failing agent:  {failing_agent_name or '—'}",
                f"Exit code:      {exit_data.exit_code}",
                f"Reason:         {exit_data.reason}",
                "",
                f"Run time: {run_time_seconds:.2f} s",
            ]
            if exit_data.return_value and exit_data.return_value.strip().startswith(
                "Traceback"
            ):
                lines.append("")
                lines.append(exit_data.return_value)
        case _:
            border_style = "red"
            lines = [f"Exit code: {getattr(exit_data, 'exit_code', '?')}"]

    return Panel(
        "\n".join(lines),
        title="Exit",
        border_style=border_style,
    )
