import argparse
import json


def register_commands(subparsers: argparse._SubParsersAction) -> None:
    p = subparsers.add_parser(
        "monitor",
        help="Monitor addresses (WS fills/userEvents/ledger)",
        description="monitor: monitor WS events for one or more addresses and push messages to an OpenClaw target.",
    )
    sp = p.add_subparsers(dest="monitor_cmd", required=True, title="Subcommands")

    run_p = sp.add_parser("run", help="Start monitoring")
    run_p.add_argument("--user", action="append", default=[], help="Address to monitor (repeatable)")
    run_p.add_argument("--target", default=None, help="OpenClaw message target (required)")
    run_p.add_argument("--min-notional-usd", type=float, default=None, help="Drop events below this notional (USD)")
    run_p.add_argument("--dedupe-window-seconds", type=int, default=None, help="Dedupe TTL seconds (avoid duplicate pushes)")
    run_p.add_argument("--language", default=None, help="Message language: zh/en (default: zh)")
    run_p.add_argument("--config", default=None, help="JSON config path (users/target/ws/language, etc.)")
    run_p.add_argument("--ws-url", default=None, help="WebSocket URL (optional; default Hyperliquid WS)")

    stop_p = sp.add_parser("stop", help="Stop monitoring (stop specific user(s) or all)")
    stop_p.add_argument("--target", required=True, help="OpenClaw message target (must match the running process)")
    stop_p.add_argument("--user", action="append", required=True, help="Address to stop (repeatable). Special value: all=stop everything")
    stop_p.add_argument("--language", default=None, help="Message language: zh/en (optional)")


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

    mc = str(getattr(args, "monitor_cmd", "") or "")
    if mc == "stop":
        from hl1m_cli.copytrade.monitor import monitor as monitor_mod

        target = str(getattr(args, "target") or "").strip()
        if not target:
            raise SystemExit("monitor stop requires --target")

        raw_users = list(getattr(args, "user", []) or [])
        users_norm = [str(u).strip() for u in raw_users if str(u).strip()]
        if not users_norm:
            raise SystemExit("monitor stop requires --user (or --user all)")

        stop_users: list[str]
        if any(str(u).strip().lower() == "all" for u in users_norm):
            stop_users = ["*"]
        else:
            stop_users = users_norm

        req_path = monitor_mod._monitor_stop_req_path(target)  # intentional: internal helper
        existing: dict[str, object] = {}
        try:
            with open(req_path, "r", encoding="utf-8") as f:
                existing = json.load(f) if f.readable() else {}
        except FileNotFoundError:
            existing = {}
        except Exception:
            existing = {}

        prev = existing.get("stopUsers") if isinstance(existing, dict) else None
        prev_list = prev if isinstance(prev, list) else []
        prev_set = {str(x).strip() for x in prev_list if str(x).strip()}
        for u in stop_users:
            prev_set.add(str(u).strip())

        with open(req_path, "w", encoding="utf-8") as f:
            json.dump({"stopUsers": sorted(prev_set)}, f, ensure_ascii=False, indent=2)

        return True

    if mc != "run":
        raise SystemExit(f"unknown monitor command: {mc}")

    from hl1m_cli.copytrade._shared.hyperliquid_constants import DEFAULT_WS_URL
    from hl1m_cli.copytrade.monitor.monitor import run as monitor_run

    ns = argparse.Namespace(
        user=list(getattr(args, "user", []) or []),
        stop_user=[],
        target=getattr(args, "target", None),
        min_notional_usd=getattr(args, "min_notional_usd", None),
        dedupe_window_seconds=getattr(args, "dedupe_window_seconds", None),
        language=getattr(args, "language", None),
        config=getattr(args, "config", None),
        ws_url=str(getattr(args, "ws_url", None) or DEFAULT_WS_URL),
    )

    rc = int(monitor_run(ns) or 0)
    if rc != 0:
        raise SystemExit(rc)
    return True


__all__ = ["register_commands", "handle_command"]

