"""
Prometheus/VictoriaMetrics name sanitization utilities.

Prometheus naming rules:
- Metric names must match: [a-zA-Z_:][a-zA-Z0-9_:]*
- Label names must match: [a-zA-Z_][a-zA-Z0-9_]*
- Label values can be any UTF-8 string (no sanitization needed)
"""
from __future__ import annotations

from typing import TYPE_CHECKING

if TYPE_CHECKING:
    from .model import Entry


def sanitize_metric_name(name: str) -> str:
    """
    Sanitize a metric name to comply with Prometheus naming rules.

    Rules:
    - First character must be [a-zA-Z_:]
    - Subsequent characters must be [a-zA-Z0-9_:]
    - All other characters are replaced with underscore

    Args:
        name: Original metric name

    Returns:
        Sanitized metric name
    """
    if not name:
        return "_"

    # Replace invalid characters with underscores
    sanitized = ""
    for i, char in enumerate(name):
        if i == 0:
            # First character: must be [a-zA-Z_:]
            if char.isalpha() or char in ("_", ":"):
                sanitized += char
            else:
                sanitized += "_"
        else:
            # Subsequent characters: must be [a-zA-Z0-9_:]
            if char.isalnum() or char in ("_", ":"):
                sanitized += char
            else:
                sanitized += "_"

    return sanitized


def sanitize_label_name(name: str) -> str:
    """
    Sanitize a label (tag) name to comply with Prometheus naming rules.

    Rules:
    - First character must be [a-zA-Z_]
    - Subsequent characters must be [a-zA-Z0-9_]
    - All other characters are replaced with underscore

    Args:
        name: Original label name

    Returns:
        Sanitized label name
    """
    if not name:
        return "_"

    # Replace invalid characters with underscores
    sanitized = ""
    for i, char in enumerate(name):
        if i == 0:
            # First character: must be [a-zA-Z_]
            if char.isalpha() or char == "_":
                sanitized += char
            else:
                sanitized += "_"
        else:
            # Subsequent characters: must be [a-zA-Z0-9_]
            if char.isalnum() or char == "_":
                sanitized += char
            else:
                sanitized += "_"

    return sanitized


def sanitize_entry(entry: Entry) -> Entry:
    """
    Sanitize an Entry object's series name and tag names.

    Args:
        entry: Entry object to sanitize

    Returns:
        New Entry object with sanitized names
    """
    # Import here to avoid circular import at module level
    from .model import Entry as EntryClass  # noqa: PLC0415

    sanitized_tags = {
        sanitize_label_name(k): v
        for k, v in entry.tags.items()
    }

    return EntryClass(
        value=entry.value,
        series=sanitize_metric_name(entry.series),
        tags=sanitized_tags,
        time=entry.ns_time,
        mode=entry.mode,
    )
