"""Rule registry — register and look up validation rules."""

from __future__ import annotations

from typing import Callable

from hatchdx.validator.models import ValidationResult, ValidationRule

# Global rule store, populated at import time by the decorator.
_rules: list[ValidationRule] = []


def register_rule(
    *,
    name: str,
    category: str,
    severity: str,
    description: str,
) -> Callable:
    """Decorator that registers a validation rule function.

    Usage::

        @register_rule(
            name="tool_names_snake_case",
            category="naming",
            severity="warning",
            description="Tool names should use snake_case with a service prefix.",
        )
        def check_tool_names_snake_case(tools, **kwargs):
            ...  # return list[ValidationResult]
    """
    def decorator(fn: Callable[..., list[ValidationResult]]) -> Callable[..., list[ValidationResult]]:
        rule = ValidationRule(
            name=name,
            category=category,
            severity=severity,
            description=description,
            check=fn,
        )
        _rules.append(rule)
        # Attach the rule object to the function for easy access in tests.
        fn._rule = rule  # type: ignore[attr-defined]
        return fn

    return decorator


def get_rules(
    *,
    category: str | None = None,
    severity: str | None = None,
) -> list[ValidationRule]:
    """Return registered rules, optionally filtered by category and/or severity."""
    result = _rules
    if category is not None:
        result = [r for r in result if r.category == category]
    if severity is not None:
        result = [r for r in result if r.severity == severity]
    return list(result)


def clear_rules() -> None:
    """Remove all registered rules. Intended for testing only."""
    _rules.clear()
