"""Argument parsing for valn8n CLI."""

import argparse
from importlib.metadata import version


def build_parser() -> argparse.ArgumentParser:
    """Build the top-level argument parser with subcommands."""
    parser = argparse.ArgumentParser(
        prog="valn8n",
        description="A validator for n8n JSON workflow files.",
    )
    parser.add_argument(
        "--version",
        action="version",
        version=f"valn8n {version('valn8n')}",
    )

    subparsers = parser.add_subparsers(dest="command")

    check = subparsers.add_parser(
        "check",
        help="Validate n8n workflow files",
    )
    check.add_argument(
        "paths",
        nargs="+",
        help="Files or directories to check",
    )
    check.add_argument(
        "--fmt",
        choices=["rich", "text", "lst", "json", "csv"],
        default="rich",
        dest="output_format",
        help="Output format (default: rich)",
    )
    check.add_argument(
        "--select",
        type=lambda s: set(s.split(",")),
        default=None,
        help="Only check specific rules or prefixes (comma-separated, e.g. WF0001,ND0102,IO)",
    )
    check.add_argument(
        "--ignore",
        type=lambda s: set(s.split(",")),
        default=None,
        help="Skip specific rules or prefixes (comma-separated, e.g. WF0003,IO)",
    )
    check.add_argument(
        "--extend-select",
        type=lambda s: set(s.split(",")),
        default=None,
        help="Re-include rules or prefixes after --ignore (comma-separated, e.g. ND0504)",
    )
    check.add_argument(
        "--suggestions",
        choices=["none", "short", "full"],
        default="full",
        help="Suggestion detail in diagnostics (default: full)",
    )
    check.add_argument(
        "--tolerate-node-keys",
        default="",
        dest="tolerate_node_keys",
        help="Comma-separated node keys to tolerate in ND0201, or '*' for all (default: '')",
    )
    check.add_argument(
        "--strict-only",
        action="store_true",
        dest="strict_only",
        help="Only run strict rules (ND01xx-ND04xx)",
    )
    check.add_argument(
        "-q",
        "--quiet",
        action="store_true",
        help="Quiet mode (summary only)",
    )

    subparsers.add_parser(
        "rule",
        help="List all registered rules",
    )

    return parser
