"""Decision explanation engine."""

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

from bilgeai.optimizer.models import TrainingConfig


def explain_config(config: TrainingConfig, console: Console | None = None) -> str:
    """Format all explanations for display."""
    if console is None:
        console = Console()

    lines = []
    for i, exp in enumerate(config.explanations, 1):
        source_tag = f"[{exp.source}]"
        conf_pct = f"{exp.confidence * 100:.0f}%"

        lines.append(f"{i}. {exp.decision}")
        lines.append(f"   Reason: {exp.reason}")
        lines.append(f"   Source: {source_tag}, Confidence: {conf_pct}")

        if exp.alternatives:
            alts = ", ".join(exp.alternatives)
            lines.append(f"   Alternatives: {alts}")
        lines.append("")

    text = "\n".join(lines)
    console.print(Panel(text, title="Configuration Decisions", expand=False))
    return text
