"""Template validation — check variable references against provider type."""

from __future__ import annotations

import re

from notify_bridge_core.providers.base import ServiceProviderType
from notify_bridge_core.templates.variables import registry


def validate_template(
    template_str: str,
    provider_type: ServiceProviderType,
) -> list[str]:
    """Validate a template string against available variables for a provider type.

    Returns a list of warning messages (empty if valid).
    This is a best-effort check — it looks for {{ var }} references
    and warns about unknown top-level variables.
    """
    warnings: list[str] = []
    available = registry.get_variable_names(provider_type)

    # Also allow common runtime variables not in the registry
    runtime_vars = {
        "target_type", "has_videos", "has_photos",
        "has_oversized_videos", "max_video_size", "max_video_size_mb",
        "added_assets", "assets", "albums",
        "raw_payload", "event_type_raw", "source_ip",
        # bridge_self self-monitoring variables.
        "failure_type", "subject_id", "subject_name", "count",
        "threshold", "last_error", "details",
    }
    allowed = available | runtime_vars

    # Find all {{ var }} and {{ var.attr }} references
    pattern = re.compile(r"\{\{-?\s*(\w+)")
    referenced = set()
    for match in pattern.finditer(template_str):
        referenced.add(match.group(1))

    # Also find {% for x in var %} loop variables
    for_pattern = re.compile(r"\{%-?\s*for\s+\w+\s+in\s+(\w+)")
    for match in for_pattern.finditer(template_str):
        referenced.add(match.group(1))

    # Also find {% if var %} conditionals
    if_pattern = re.compile(r"\{%-?\s*if\s+(\w+)")
    for match in if_pattern.finditer(template_str):
        referenced.add(match.group(1))

    # Filter out loop variables (from {% for x in ... %})
    loop_vars = set()
    loop_var_pattern = re.compile(r"\{%-?\s*for\s+(\w+)\s+in")
    for match in loop_var_pattern.finditer(template_str):
        loop_vars.add(match.group(1))

    # Check for unknown variables
    for var in referenced - allowed - loop_vars:
        warnings.append(f"Unknown variable '{var}' for provider type '{provider_type.value}'")

    return warnings
