from __future__ import annotations

import typer

from hytop.net.collector import parse_kind_filter, parse_name_filter
from hytop.net.service import run_monitor

app = typer.Typer(
    add_completion=False,
    context_settings={"help_option_names": ["-h", "--help"]},
    help="Network monitoring commands.",
)


@app.callback(invoke_without_command=True)
def net(
    ctx: typer.Context,
    kind: str = typer.Option(
        "all",
        "--kind",
        help="Network kind to monitor: all, eth, ib.",
    ),
    ifaces: str = typer.Option(
        "",
        "--ifaces",
        help="Comma-separated interface names to include.",
    ),
    iec: bool = typer.Option(
        False,
        "--iec",
        help="Use IEC binary prefixes KiB/MiB/GiB instead of SI prefixes kB/MB/GB.",
    ),
) -> None:
    """Network monitoring commands."""
    if ctx.obj is None:
        typer.echo("argument error: global options not available", err=True)
        raise typer.Exit(code=2)
    if kind not in {"all", "eth", "ib"}:
        typer.echo("argument error: --kind must be one of all/eth/ib", err=True)
        raise typer.Exit(code=2)

    hosts = ctx.obj["hosts"]
    interval = ctx.obj["interval"]
    window_value = ctx.obj["window"]
    timeout_value = ctx.obj.get("timeout")
    include_filter = parse_name_filter(ifaces)
    code = run_monitor(
        hosts=hosts,
        kind_filter=parse_kind_filter(kind),
        include=include_filter,
        window=window_value,
        interval=interval,
        timeout=timeout_value,
        iec=iec,
    )
    raise typer.Exit(code=code)
