from __future__ import annotations

import argparse
import json

from common import ROOT, iter_model_card_paths, read_yaml_mapping


def load_cards(include_examples: bool = False) -> list[dict]:
    cards: list[dict] = []
    for path in iter_model_card_paths(include_examples=include_examples):
        data = read_yaml_mapping(path)
        data["_path"] = str(path.relative_to(ROOT)).replace("\\", "/")
        cards.append(data)
    return cards


def print_table(cards: list[dict]) -> None:
    rows = []
    for card in cards:
        rows.append(
            [
                str(card.get("id", "")),
                str(card.get("status", "")),
                ",".join(card.get("task") or []),
                str(card.get("deployment", {}).get("runtime", "")),
                str(card.get("deployment", {}).get("served_model_name", "")),
            ]
        )

    headers = ["id", "status", "tasks", "runtime", "served_name"]
    widths = [
        max(len(row[index]) for row in rows + [headers])
        for index in range(len(headers))
    ]

    print("  ".join(header.ljust(widths[index]) for index, header in enumerate(headers)))
    print("  ".join("-" * width for width in widths))
    for row in rows:
        print("  ".join(value.ljust(widths[index]) for index, value in enumerate(row)))


def main() -> int:
    parser = argparse.ArgumentParser(description="List model cards.")
    parser.add_argument("--json", action="store_true", help="Print JSON instead of a table.")
    parser.add_argument(
        "--include-examples",
        action="store_true",
        help="Include example cards from registry/model-cards/examples.",
    )
    args = parser.parse_args()

    cards = load_cards(include_examples=args.include_examples)
    if args.json:
        print(json.dumps(cards, ensure_ascii=False, indent=2, default=str))
    elif cards:
        print_table(cards)
    else:
        print("No model cards found.")
    return 0


if __name__ == "__main__":
    raise SystemExit(main())
