"""Internal helpers for the ``agents config`` command group.

Provides pure key-normalisation, validation, and secret-masking utilities
used by ``config.py``.  Extracted to keep ``config.py`` under the
500-line limit.  Functions here have no side effects and do not call
``ConfigService``.
"""

from __future__ import annotations

import re
from typing import Any

import typer

from cleveragents.application.services.config_service import _REGISTRY

# ---------------------------------------------------------------------------
# Secret helpers
# ---------------------------------------------------------------------------

_SECRET_PATTERNS: re.Pattern[str] = re.compile(
    r"(api[_\-]?key|token|secret|password)", re.IGNORECASE
)


def _is_secret_key(key: str) -> bool:
    """Return ``True`` when *key* looks like it stores a secret."""
    return _SECRET_PATTERNS.search(key) is not None


def _mask_value(value: str) -> str:
    """Replace a value with ``****``."""
    return "****"


# ---------------------------------------------------------------------------
# Key helpers
# ---------------------------------------------------------------------------


def _normalize_key(key: str) -> str:
    """Pass-through normalisation — keys are matched as-is against the registry.

    Backward compatibility: underscores are converted to dots so that
    ``log_level`` resolves to ``core.log.level`` if there is a single
    match.  If the key already exists in the registry, it is returned
    unchanged.
    """
    stripped = key.strip()
    if stripped in _REGISTRY:
        return stripped
    # Try underscore-to-dot conversion
    dotted = stripped.replace("_", ".")
    if dotted in _REGISTRY:
        return dotted
    return stripped


def _validate_key(key: str) -> str:
    """Validate and normalise *key*, raising :class:`typer.BadParameter` on failure."""
    normalized = _normalize_key(key)
    if not normalized:
        raise typer.BadParameter("Key must not be empty.")
    if normalized not in _REGISTRY:
        valid_sample = ", ".join(sorted(_REGISTRY)[:8])
        raise typer.BadParameter(
            f"Unknown configuration key: '{key}' "
            f"(normalized: '{normalized}'). "
            f"Valid keys include: {valid_sample} ..."
        )
    return normalized


def _env_var_for_key(key: str) -> str:
    """Return the environment-variable name for a registered key."""
    entry = _REGISTRY.get(key)
    if entry is not None:
        return entry.env_var
    return f"CLEVERAGENTS_{key.upper().replace('.', '_').replace('-', '_')}"


def _settings_defaults() -> dict[str, Any]:
    """Return all registered config keys mapped to their default values."""
    return {key: entry.default for key, entry in _REGISTRY.items()}
