import argparse
import sys
from importlib.metadata import version

from .ui.watch import watch


def main() -> None:
    parser = argparse.ArgumentParser(description="Diagnose why your network is slow")
    parser.add_argument(
        "-v",
        "--version",
        action="version",
        version=f"%(prog)s {version('yslow')}",
    )
    parser.add_argument(
        "-w",
        "--watch",
        nargs="?",
        const=30,
        type=int,
        metavar="SECONDS",
        help="Continuous monitoring mode (default: 30s interval)",
    )
    parser.add_argument(
        "-n",
        "--count",
        type=int,
        default=None,
        metavar="N",
        help="Number of checks to run (default: 1, or unlimited with --watch). 0 = unlimited.",
    )
    args = parser.parse_args()

    interval = args.watch if args.watch is not None else 30
    if args.watch is not None and (interval < 5 or interval > 3600):
        print("Error: interval must be between 5 and 3600 seconds", file=sys.stderr)
        sys.exit(1)

    # Default count: 0 (infinite) when --watch is used, 1 otherwise
    if args.count is not None:
        count = args.count
    elif args.watch is not None:
        count = 0
    else:
        count = 1

    watch(interval=interval, count=count)
