"""Output formatting: rich table, JSON, and markdown."""

from __future__ import annotations

import json

from rich.console import Console
from rich.table import Table
from rich.text import Text

from mcp_diet.analyzer import AnalysisSummary, ToolAnalysis


GRADE_COLORS = {
    "A": "green",
    "B": "blue",
    "C": "yellow",
    "D": "red",
    "F": "bold red",
}


def _grade_text(grade: str) -> Text:
    return Text(grade, style=GRADE_COLORS.get(grade, ""))


def print_table(summary: AnalysisSummary, server_name: str | None = None) -> None:
    """Print a rich table to the terminal."""
    console = Console()

    title = "MCP Tool Analysis"
    if server_name:
        title += f" — {server_name}"

    table = Table(title=title, show_lines=True)
    table.add_column("Tool", style="cyan", no_wrap=True)
    table.add_column("Tokens", justify="right")
    table.add_column("% Budget", justify="right")
    table.add_column("Depth", justify="right")
    table.add_column("Desc Len", justify="right")
    table.add_column("Grade", justify="center")

    for t in summary.tools:
        table.add_row(
            t.name,
            f"{t.tokens:,}",
            f"{t.budget_pct:.1f}%",
            str(t.schema_depth),
            str(t.desc_length),
            _grade_text(t.grade),
        )

    console.print(table)
    console.print()

    # Summary footer
    console.print(f"[bold]Total tokens:[/bold] {summary.total_tokens:,} / {summary.budget:,} ({summary.budget_pct:.1f}%)")
    console.print(f"[bold]Est. cost per 1000 calls:[/bold] ${summary.cost_per_1000:.4f}")

    if summary.top_offenders:
        console.print(f"[bold]Top offenders:[/bold]")
        for t in summary.top_offenders:
            console.print(f"  {t.name}: {t.tokens:,} tokens ({t.grade})")

    console.print()


def to_json(summary: AnalysisSummary, server_name: str | None = None) -> str:
    """Return JSON representation."""
    return json.dumps(
        {
            "server": server_name,
            "total_tokens": summary.total_tokens,
            "budget": summary.budget,
            "budget_pct": round(summary.budget_pct, 2),
            "cost_per_1000_calls": round(summary.cost_per_1000, 6),
            "tools": [
                {
                    "name": t.name,
                    "tokens": t.tokens,
                    "budget_pct": round(t.budget_pct, 2),
                    "schema_depth": t.schema_depth,
                    "desc_length": t.desc_length,
                    "grade": t.grade,
                }
                for t in summary.tools
            ],
            "top_offenders": [t.name for t in summary.top_offenders],
        },
        indent=2,
    )


def to_markdown(summary: AnalysisSummary, server_name: str | None = None) -> str:
    """Return markdown representation."""
    lines = []
    header = "## MCP Tool Analysis"
    if server_name:
        header += f" — {server_name}"
    lines.append(header)
    lines.append("")
    lines.append("| Tool | Tokens | % Budget | Depth | Desc Len | Grade |")
    lines.append("|------|-------:|--------:|------:|---------:|:-----:|")

    for t in summary.tools:
        lines.append(
            f"| {t.name} | {t.tokens:,} | {t.budget_pct:.1f}% | {t.schema_depth} | {t.desc_length} | {t.grade} |"
        )

    lines.append("")
    lines.append(f"**Total tokens:** {summary.total_tokens:,} / {summary.budget:,} ({summary.budget_pct:.1f}%)")
    lines.append(f"**Est. cost per 1000 calls:** ${summary.cost_per_1000:.4f}")

    if summary.top_offenders:
        lines.append("")
        lines.append("**Top offenders:**")
        for t in summary.top_offenders:
            lines.append(f"- {t.name}: {t.tokens:,} tokens ({t.grade})")

    lines.append("")
    return "\n".join(lines)


def output_report(
    summary: AnalysisSummary,
    fmt: str = "table",
    server_name: str | None = None,
) -> None:
    """Output the analysis report in the requested format."""
    if fmt == "json":
        print(to_json(summary, server_name))
    elif fmt == "markdown":
        print(to_markdown(summary, server_name))
    else:
        print_table(summary, server_name)
