import argparse


def register_commands(subparsers: argparse._SubParsersAction) -> None:
    p = subparsers.add_parser(
        "copy",
        help="Copy-trading module (start/stop/config/wallet)",
        description="copy: copy-trading entrypoint (start/stop, hot-update params, and init copytrade wallet).",
    )
    sp = p.add_subparsers(dest="ct_cmd", required=True, title="Subcommands")

    start = sp.add_parser("start", help="Start copy trading (follow leader fills)")
    start.add_argument("--leader", default=None, help="Leader address (0x...)")
    start.add_argument("--target", default=None, help="OpenClaw message target (status/execution messages)")
    start.add_argument("--scale", type=float, default=1.0, help="Position size scale (default: 1.0)")
    start.add_argument("--max-notional-usd", type=float, default=None, help="Max notional per coin (USD). Empty means unlimited")
    start.add_argument("--max-leverage", type=float, default=None, help="Max leverage (best-effort). Empty means unlimited")
    start.add_argument("--slippage", type=float, default=0.05, help="Slippage tolerance for market orders (default: 0.05=5%%)")
    start.add_argument("--coins", default="", help='Coin allowlist (comma-separated). Empty means all. e.g. "BTC,HYPE,xyz:TSLA"')
    start.add_argument("--take-profit-pct", type=float, default=None, help="Take-profit percent (e.g. 0.1=+10%%). Empty disables")
    start.add_argument("--stop-loss-pct", type=float, default=None, help="Stop-loss percent (e.g. 0.05=-5%%). Empty disables")
    start.add_argument("--language", default="zh", help="Message language: zh/en (default: zh)")

    stop = sp.add_parser("stop", help="Stop copy trading process (by target)")
    stop.add_argument("--target", required=True, help="OpenClaw target (must match the running process)")
    stop.add_argument("--language", default=None, help="Message language: zh/en (optional)")

    cfg = sp.add_parser("config", help="Hot-update runtime copy parameters")
    cfg.add_argument("--target", required=True, help="OpenClaw target (must match the running process)")
    cfg.add_argument("--scale", type=float, default=None, help="Update scale (empty means unchanged)")
    cfg.add_argument("--max-notional-usd", default=None, help="Update max notional per coin (USD). Use 'off' to disable")
    cfg.add_argument("--max-leverage", default=None, help="Update max leverage. Use 'off' to disable")
    cfg.add_argument("--take-profit-pct", default=None, help="Update take-profit percent. Use 'off' to disable")
    cfg.add_argument("--stop-loss-pct", default=None, help="Update stop-loss percent. Use 'off' to disable")
    cfg.add_argument("--coins", default=None, help="Update coin allowlist (comma-separated). Use 'off' to allow all")

    wallet = sp.add_parser("wallet", help="Init copytrade wallet (separate from trade wallet)")
    wallet.add_argument("--addr", "--address", dest="addr", required=False, help="Optional wallet address (0x...). If omitted, derive from --pri_key")
    wallet.add_argument("--pri_key", required=True, help="Wallet private key (0x + 64 hex)")


def handle_command(args: argparse.Namespace) -> bool:
    if getattr(args, "command", None) != "copy":
        return False

    if args.ct_cmd == "start":
        from .copy.copy_main import run as copy_run

        ns = argparse.Namespace(**vars(args))
        setattr(ns, "stop", False)
        rc = int(copy_run(ns) or 0)
        if rc != 0:
            raise SystemExit(rc)
        return True

    if args.ct_cmd == "stop":
        from .copy.copy_main import run as copy_run

        ns = argparse.Namespace(**vars(args))
        setattr(ns, "stop", True)
        rc = int(copy_run(ns) or 0)
        print("copy stopped")
        if rc != 0:
            raise SystemExit(rc)
        return True

    if args.ct_cmd == "config":
        from .copy.copy_update_params import run as update_params_run

        rc = int(update_params_run(args) or 0)
        if rc != 0:
            raise SystemExit(rc)
        return True

    if args.ct_cmd == "wallet":
        from .copy.wallet import init_wallet

        init_wallet(getattr(args, "addr", None), getattr(args, "pri_key", None))
        return True

    raise SystemExit(f"unknown copy command: {args.ct_cmd}")


__all__ = ["register_commands", "handle_command"]

