"""Crawl command -- discover MCP servers from public registries."""

from __future__ import annotations

import argparse
import asyncio
import sys
from pathlib import Path

import orjson


def _crawl_registries_command(cli, args: argparse.Namespace) -> int:  # type: ignore[no-untyped-def]
    """Handle `navil crawl registries`."""
    from navil.crawler.registry_crawler import RegistryCrawler

    limit = args.limit or 0
    output_dir = Path(args.output)
    output_dir.mkdir(parents=True, exist_ok=True)

    print(f"Crawling registries (limit={limit or 'unlimited'})...")

    crawler = RegistryCrawler(limit=limit)
    results = asyncio.run(crawler.crawl())

    if not results:
        print("No servers discovered.", file=sys.stderr)
        return 1

    # Write each result as a JSON file
    for i, r in enumerate(results):
        fname = f"{r.source}_{i:04d}.json"
        path = output_dir / fname
        path.write_bytes(orjson.dumps(r.to_dict(), option=orjson.OPT_INDENT_2))

    print(f"Discovered {len(results)} servers, written to {output_dir}/")
    return 0


def register(subparsers: argparse._SubParsersAction, cli_class: type) -> None:
    """Register the crawl subcommand."""
    crawl_parser = subparsers.add_parser("crawl", help="Crawl MCP registries")
    crawl_sub = crawl_parser.add_subparsers(dest="crawl_command")

    reg_parser = crawl_sub.add_parser("registries", help="Discover MCP servers from registries")
    reg_parser.add_argument(
        "--output",
        "-o",
        default="crawl_results",
        help="Output directory for crawl results (default: crawl_results/)",
    )
    reg_parser.add_argument(
        "--limit",
        type=int,
        default=0,
        help="Max number of servers to discover (0 = unlimited)",
    )
    reg_parser.set_defaults(func=lambda cli, args: _crawl_registries_command(cli, args))
