"""Output formatting for the Kanoniv CLI."""
from __future__ import annotations

import json
import sys
from typing import Any


def print_json(data: Any) -> None:
    """Pretty-print JSON to stdout."""
    json.dump(data, sys.stdout, indent=2, default=str)
    sys.stdout.write("\n")


def print_table(headers: list[str], rows: list[list[str]]) -> None:
    """Print a simple ASCII table to stdout."""
    if not rows:
        for h in headers:
            sys.stdout.write(h + "  ")
        sys.stdout.write("\n(no results)\n")
        return

    # Compute column widths
    widths = [len(h) for h in headers]
    for row in rows:
        for i, cell in enumerate(row):
            if i < len(widths):
                widths[i] = max(widths[i], len(cell))

    # Header
    header_line = "  ".join(h.ljust(widths[i]) for i, h in enumerate(headers))
    sys.stdout.write(header_line + "\n")
    sys.stdout.write("  ".join("-" * w for w in widths) + "\n")

    # Rows
    for row in rows:
        line = "  ".join(
            (row[i] if i < len(row) else "").ljust(widths[i])
            for i in range(len(headers))
        )
        sys.stdout.write(line + "\n")


def print_error(msg: str) -> None:
    """Print an error message to stderr and exit."""
    sys.stderr.write(f"error: {msg}\n")
    sys.exit(1)


def print_success(msg: str) -> None:
    """Print a success message to stdout."""
    sys.stdout.write(f"{msg}\n")
