import json
from django import template
from django.utils.safestring import mark_safe
from django.utils.html import escape

register = template.Library()


@register.filter(name="pretty_json")
def pretty_json(value):
    """Pretty-print a JSON string or Python object for display inside <pre>.

    Returns an HTML-escaped, pretty-formatted JSON string (marked safe).
    """
    try:
        if isinstance(value, str):
            obj = json.loads(value)
        else:
            obj = value
        pretty = json.dumps(obj, indent=2, default=str, sort_keys=True)
    except Exception:
        try:
            pretty = str(value) if value is not None else "{}"
        except Exception:
            pretty = "{}"

    return mark_safe(escape(pretty))
