from __future__ import annotations

import json
from typing import Iterable, Literal, Sequence

import typer
import yaml
from prettytable import PrettyTable

OutputFormat = Literal["table", "json", "yaml"]


def ensure_output_format(value: str) -> OutputFormat:
    v = (value or "").strip().lower()
    if v not in ("table", "json", "yaml"):
        raise typer.BadParameter(
            "Invalid output format. Use one of: table, json, yaml."
        )
    return v  # type: ignore[return-value]


def emit_structured(payload: object, output: OutputFormat) -> None:
    if output == "json":
        typer.echo(json.dumps(payload, indent=2))
        return
    if output == "yaml":
        typer.echo(
            yaml.safe_dump(payload, sort_keys=False, default_flow_style=False).rstrip()
        )
        return
    raise ValueError("emit_structured only supports json|yaml")


def build_table(
    field_names: Sequence[str], rows: Iterable[Sequence[object]]
) -> PrettyTable:
    t = PrettyTable()
    t.field_names = list(field_names)
    for name in field_names:
        t.align[name] = "l"
    for row in rows:
        t.add_row([_cell(v) for v in row])
    return t


def _cell(v: object) -> str:
    if v is None:
        return ""
    if isinstance(v, bool):
        return "true" if v else "false"
    return str(v)
