"""
Template filters for safe error formatting.
"""

import html

from django import template
from django.utils.safestring import mark_safe

register = template.Library()


@register.filter
def format_k8s_error(error_data):
    """
    Template filter to safely format Kubernetes error data.
    Usage: {{ error_data|format_k8s_error }}

    Args:
        error_data: Dictionary with structure from _format_kubernetes_error method
                   or a simple string

    Returns:
        Safely formatted HTML string
    """
    if not error_data:
        return ""

    if not error_data.get("has_list", False):
        return html.escape(error_data.get("message", ""))

    message = html.escape(error_data.get("message", ""))
    errors = error_data.get("errors", [])

    if not errors:
        return message

    escaped_errors = [html.escape(str(error)) for error in errors]
    error_items = "".join(f"<li>{error}</li>" for error in escaped_errors)

    if message:
        return mark_safe(f"{message}<ul>{error_items}</ul>")
    else:
        return mark_safe(f"<ul>{error_items}</ul>")
