import argparse


def register_commands(subparsers: argparse._SubParsersAction) -> None:
    p = subparsers.add_parser(
        "analyze",
        help="Analyze an address (positions/fills/pnl history)",
        description="analyze: analyze a single address (positions, fills, pnl history, etc.).",
    )
    sp = p.add_subparsers(dest="analyze_cmd", required=True, title="Subcommands")

    one = sp.add_parser("address", help="Analyze one address")
    one.add_argument("--addr", "--address", dest="addr", required=True, help="Wallet address to analyze (0x...)")
    one.add_argument("--days", type=int, default=None, help="Window size in days (default: 30)")
    one.add_argument("--out", default=None, help="Output Markdown file path (optional)")
    one.add_argument("--out-json", default=None, help="Output JSON file path (optional)")
    one.add_argument("--no-aggregate", action="store_true", help="Disable aggregation (prefer raw time series output)")
    one.add_argument("--top-n", type=int, default=None, help="Top N summary (default: 10)")


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

    ac = str(getattr(args, "analyze_cmd", "") or "")
    if ac != "address":
        raise SystemExit(f"unknown analyze command: {ac}")

    from hl1m_cli.copytrade._shared.hyperliquid_constants import DEFAULT_HTTP_BASE_URL
    from hl1m_cli.copytrade.analyze.analyze import run as analyze_run

    ns = argparse.Namespace(
        user=str(getattr(args, "addr")),
        out=getattr(args, "out", None),
        out_json=getattr(args, "out_json", None),
        base_url=DEFAULT_HTTP_BASE_URL,
        no_aggregate=bool(getattr(args, "no_aggregate", False)),
        days=int(getattr(args, "days", 30) or 30),
        top_n=int(getattr(args, "top_n", 10) or 10),
    )
    rc = int(analyze_run(ns) or 0)
    if rc != 0:
        raise SystemExit(rc)
    return True


__all__ = ["register_commands", "handle_command"]

