"""Console entry point for printing ML lab programs."""

from __future__ import annotations

import argparse
from typing import Sequence

from .labs import get_lab_programs
from .printer import format_lab, print_all_labs
from .docs import print_all_docs, print_docs_by_library


def build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(
        prog="purb",
        description="Print ML lab programs packaged inside the purb distribution.",
    )
    parser.add_argument(
        "--list",
        action="store_true",
        help="Show the available labs without printing the full content.",
    )
    parser.add_argument(
        "--lab",
        type=int,
        metavar="INDEX",
        help="Print a single lab by its 1-based index from the --list view.",
    )
    parser.add_argument(
        "--docs",
        type=str,
        nargs="?",
        const="all",
        metavar="LIBRARY",
        help="Print documentation. Use 'all' (default), 'pandas', 'sklearn', or 'pgmpy'.",
    )
    return parser


def main(argv: Sequence[str] | None = None) -> None:
    parser = build_parser()
    args = parser.parse_args(argv)
    labs = get_lab_programs()

    if args.list:
        for idx, lab in enumerate(labs, start=1):
            summary = f" - {lab.summary}" if lab.summary else ""
            print(f"{idx}. {lab.title}{summary}")
        return

    if args.lab is not None:
        index = args.lab - 1
        if not 0 <= index < len(labs):
            parser.error(f"Lab index must be between 1 and {len(labs)}")
        print(format_lab(labs[index], args.lab))
        return

    if args.docs is not None:
        if args.docs.lower() == "all":
            print_all_docs()
        else:
            try:
                print_docs_by_library(args.docs)
            except ValueError as e:
                parser.error(str(e))
        return

    print_all_labs(labs)


if __name__ == "__main__":  # pragma: no cover
    main()

