"""Unified command-line interface for TopoVec."""

from __future__ import annotations

import argparse
import importlib
import sys


def _viewer_cli():
    return importlib.import_module(".viewer.qt.cli", __package__)


def build_parser() -> argparse.ArgumentParser:
    """Build the root ``topovec`` command parser."""

    parser = argparse.ArgumentParser(
        prog="topovec",
        description="Command-line interface for TopoVec.",
    )
    subparsers = parser.add_subparsers(dest="command")
    view_parser = subparsers.add_parser(
        "view",
        prog="topovec view",
        help="Open the desktop viewer for NPZ and SAD state files.",
        description="Open the TopoVec desktop viewer for NPZ and SAD state files.",
    )
    viewer_cli = _viewer_cli()
    viewer_cli.add_view_arguments(view_parser)
    view_parser.set_defaults(handler=viewer_cli.run_view)
    return parser


def main(argv: list[str] | None = None) -> int:
    parser = build_parser()
    cli_argv = sys.argv[1:] if argv is None else list(argv)
    if not cli_argv:
        parser.print_help(sys.stderr)
        return 2

    args = parser.parse_args(cli_argv)
    handler = getattr(args, "handler", None)
    if handler is None:
        parser.print_help(sys.stderr)
        return 2

    if args.command == "view":
        return int(handler(args, argv=cli_argv[1:]))
    return int(handler(args, argv=[]))


__all__ = ["build_parser", "main"]
