# src/remoteRF/cli.py
from __future__ import annotations

import argparse
import sys
from typing import Optional, Sequence

from remoteRF.core.acc_login import main as login_main
from remoteRF.core.version import main as version_main
from remoteRF.config.config_cli import main as config_main


def build_parser() -> argparse.ArgumentParser:
    p = argparse.ArgumentParser(
        prog="remoterf",
        formatter_class=argparse.RawTextHelpFormatter,
        add_help=True,
        description=(
            "RemoteRF unified CLI\n\n"
            "Examples:\n"
            "  remoterf --login\n"
            "  remoterf -l\n"
            "  remoterf --config --addr 164.67.195.207:61005\n"
            "  remoterf -c -a 164.67.195.207:61005\n"
            "  remoterf --config --wipe\n"
            "  remoterf -v\n"
        ),
    )

    mode = p.add_mutually_exclusive_group()

    mode.add_argument("-l", "--login", action="store_true", help="Login / register (interactive).")
    mode.add_argument("-c", "--config", action="store_true", help="Configure server target / CA cert.")
    mode.add_argument("-v", "--version", action="store_true", help="Print version and exit.")

    # These are only meaningful with --config, but we accept them at top-level
    # so your UX works as requested.
    p.add_argument(
        "-a", "--addr", "-addr",
        dest="addr",
        default=None,
        help="Server address (host:port). Used with --config / -c.",
    )

    p.add_argument(
        "-w", "--wipe",
        action="store_true",
        help="Wipe local config (~/.config/remoterf). Used with --config / -c.",
    )

    p.add_argument(
        "--yes",
        action="store_true",
        help="Skip confirmation prompts (use with --config --wipe).",
    )

    return p


def main(argv: Optional[Sequence[str]] = None) -> int:
    argv = list(sys.argv[1:] if argv is None else argv)

    parser = build_parser()

    # No args => help panel
    if len(argv) == 0:
        parser.print_help()
        return 0

    args, extra = parser.parse_known_args(argv)

    # --- Version ---
    if args.version:
        if extra:
            parser.error(f"Unexpected arguments for --version: {' '.join(extra)}")
        # If your version_main supports argv, pass [].
        try:
            version_main([])
        except TypeError:
            version_main()
        return 0

    # --- Login ---
    if args.login:
        if extra:
            parser.error(f"Unexpected arguments for --login: {' '.join(extra)}")
        try:
            login_main([])
        except TypeError:
            login_main()
        return 0

    # --- Config ---
    if args.config:
        cfg_argv: list[str] = []

        # Normalize to whatever config_cli expects.
        # If your config_cli supports --wipe/--yes, pass them through.
        if args.wipe:
            cfg_argv.append("--wipe")
            if args.yes:
                cfg_argv.append("--yes")

        # Address handling
        if args.addr:
            # If config_cli expects a positional addr, pass it positionally:
            cfg_argv.append(args.addr)
            # If your config_cli instead expects --addr, switch to:
            # cfg_argv += ["--addr", args.addr]

        # Preserve any extra args for config_cli (if you want)
        cfg_argv += extra

        # If neither addr nor wipe was supplied, show config help-like message.
        if not args.addr and not args.wipe and len(extra) == 0:
            # Call config_cli with --help if it supports it; otherwise print ours.
            try:
                config_main(["--help"])
            except Exception:
                parser.error("Config mode requires --addr <host:port> or --wipe.")
            return 0

        try:
            config_main(cfg_argv)
        except TypeError:
            # Fallback if config_main does not accept argv; last resort:
            old = sys.argv[:]
            try:
                sys.argv = ["remoterf-config", *cfg_argv]
                config_main()
            finally:
                sys.argv = old
        return 0

    # If user passed only -a/-w without -c/--config, show help
    parser.print_help()
    return 0


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