from __future__ import annotations

import argparse
import sys

from unuforge.cli_commands import actions as action_commands
from unuforge.cli_commands import preset as preset_commands
from unuforge.cli_commands import profiles as profile_commands


def _build_parser() -> argparse.ArgumentParser:
    parser = argparse.ArgumentParser(prog="python3 -m unuforge.cli")
    subparsers = parser.add_subparsers(dest="command", required=True)

    action_commands.register(subparsers)
    preset_commands.register(subparsers)
    profile_commands.register(subparsers)
    return parser


def main(argv: list[str] | None = None) -> int:
    parser = _build_parser()
    args, passthrough_args = parser.parse_known_args(argv)
    setattr(args, "passthrough_args", passthrough_args)
    handler = getattr(args, "handler", None)
    if handler is None:
        parser.error("missing command handler")
    try:
        return handler(args)
    except Exception as exc:
        print(f"ERROR: {exc}", file=sys.stderr)
        return 1


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