"""Security utilities for mustache template processing."""

import re
from typing import Any

# Regex pattern for simple variables only - same as frontend
SIMPLE_VARIABLE_PATTERN = re.compile(r"\{\{([a-zA-Z_][a-zA-Z0-9_]*)\}\}")

# Patterns for complex mustache syntax that we want to block
DANGEROUS_PATTERNS = [
    re.compile(r"\{\{\{"),  # Triple braces (unescaped HTML in Mustache)
    re.compile(r"\{\{#"),  # Conditionals/sections start
    re.compile(r"\{\{/"),  # Conditionals/sections end
    re.compile(r"\{\{\^"),  # Inverted sections
    re.compile(r"\{\{&"),  # Unescaped variables
    re.compile(r"\{\{>"),  # Partials
    re.compile(r"\{\{!"),  # Comments
    re.compile(r"\{\{\."),  # Current context
]


def _find_mustache_patterns(template: str) -> list[str]:
    """Find all {{...}} patterns in a template using string search (no regex)."""
    patterns = []
    start = 0
    while True:
        idx = template.find("{{", start)
        if idx == -1:
            break
        end = template.find("}}", idx + 2)
        if end == -1:
            break
        patterns.append(template[idx : end + 2])
        start = end + 2
    return patterns


def validate_mustache_template(template: str) -> None:
    """Validate that a mustache template only contains simple variable substitutions.

    Raises ValueError if complex mustache syntax is detected.
    """
    if not template:
        return

    # Check for dangerous patterns
    for pattern in DANGEROUS_PATTERNS:
        if pattern.search(template):
            msg = (
                "Complex mustache syntax is not allowed. Only simple variable substitution "
                "like {{variable}} is permitted."
            )
            raise ValueError(msg)

    # Check that all {{ }} patterns are simple variables
    all_mustache_patterns = _find_mustache_patterns(template)
    for pattern in all_mustache_patterns:
        if not SIMPLE_VARIABLE_PATTERN.match(pattern):
            msg = f"Invalid mustache variable: {pattern}. Only simple variable names like {{{{variable}}}} are allowed."
            raise ValueError(msg)


def safe_mustache_render(template: str, variables: dict[str, Any]) -> str:
    """Safely render a mustache template with only simple variable substitution.

    This function performs a single-pass replacement of all {{variable}} patterns.
    Variable values that themselves contain mustache-like patterns (e.g., "{{other}}")
    will NOT be processed - they are treated as literal strings. This prevents
    injection attacks where user-controlled values could introduce new template variables.

    Args:
        template: The mustache template string
        variables: Dictionary of variables to substitute

    Returns:
        The rendered template

    Raises:
        ValueError: If template contains complex mustache syntax
    """
    # Validate template first
    validate_mustache_template(template)

    # Simple replacement - find all simple variables and replace them
    def replace_variable(match):
        var_name = match.group(1)

        # Get the variable value directly (no dot notation support)
        value = variables.get(var_name, "")

        # Convert to string
        return str(value) if value is not None else ""

    # Replace all simple variables
    return SIMPLE_VARIABLE_PATTERN.sub(replace_variable, template)
