"""Rich terminal reporter for toil analysis."""
from rich.console import Console
from rich.table import Table
from rich.panel import Panel
from ..models import ToilReport, Severity

SEVERITY_COLORS = {
    Severity.CRITICAL: "red bold",
    Severity.HIGH: "red",
    Severity.MEDIUM: "yellow",
    Severity.LOW: "cyan",
    Severity.INFO: "dim",
}


def print_report(report: ToilReport, console: Console | None = None):
    console = console or Console()
    grade_color = {"A": "green", "B": "blue", "C": "yellow", "D": "red", "F": "red bold"}.get(report.grade, "white")
    console.print(Panel(
        f"[bold]Tasks:[/] {report.total_tasks}\n"
        f"[bold]Total Toil:[/] {report.total_annual_hours:.0f} hours/year\n"
        f"[bold]Automatable:[/] [yellow]{report.automatable_hours:.0f}[/] hours/year\n"
        f"[bold]Automation Coverage:[/] {report.automation_coverage:.1f}%\n"
        f"[bold]Health Score:[/] [{grade_color}]{report.health_score:.1f}/100 (Grade {report.grade})[/]\n"
        f"[bold]Findings:[/] {len(report.findings)} "
        f"(🔴 {report.critical_count} 🟠 {report.high_count} 🟡 {report.medium_count} 🔵 {report.low_count} ⚪ {report.info_count})",
        title="⚙️ Toil Tracker Report",
        border_style=grade_color,
    ))
    if report.tasks:
        task_table = Table(title="Task Summary", show_lines=True)
        task_table.add_column("Task", width=25)
        task_table.add_column("Category", width=18)
        task_table.add_column("Frequency", width=10)
        task_table.add_column("Hours/Year", width=10, justify="right")
        task_table.add_column("ROI (months)", width=12, justify="right")
        task_table.add_column("Automatable", width=11)
        for t in sorted(report.tasks, key=lambda x: x.annual_hours, reverse=True):
            roi = f"{t.automation_roi_months:.1f}" if t.automation_roi_months < 100 else "N/A"
            auto = "[green]Yes[/]" if t.is_automatable else "[red]No[/]"
            task_table.add_row(t.name, t.category.value, t.frequency.value, f"{t.annual_hours:.0f}", roi, auto)
        console.print(task_table)
    if not report.findings:
        console.print("[green]✅ No toil issues found![/]")
        return
    table = Table(title="Findings", show_lines=True)
    table.add_column("Rule", style="bold", width=10)
    table.add_column("Severity", width=10)
    table.add_column("Task", width=25)
    table.add_column("Issue", width=45)
    table.add_column("Recommendation", width=40)
    for f in report.findings:
        sev_style = SEVERITY_COLORS.get(f.severity, "white")
        table.add_row(
            f.rule_id, f"[{sev_style}]{f.severity.value.upper()}[/]",
            f.task_name, f.description, f.recommendation,
        )
    console.print(table)
