import hashlib
from urllib.parse import urlencode
import requests  # Added to perform HTTP requests
from django import template
from django.utils.safestring import mark_safe

register = template.Library()

@register.filter
def gravatar_hash(email):
    """
    Returns the hash of the email.
    """
    email_encoded = email.strip().lower().encode('utf-8')
    email_hash = hashlib.sha256(email_encoded).hexdigest()
    return email_hash

@register.filter
def gravatar_url(email, size=20):
    """
    Returns the Gravatar URL for a given email. The URL includes parameters
    for the default image and the size.
    """
    default = "retro"
    email_hash = gravatar_hash(email)
    params = urlencode({'d': default, 's': str(size)})
    params = params.replace("&", "&amp;")
    return f"https://www.gravatar.com/avatar/{email_hash}?{params}"

@register.filter
def gravatar_profile_url(email=None):
    """
    Returns the Gravatar Profile URL for a given email.
    """
    if email is None:
        return f"https://www.gravatar.com/profile"
    email_hash = gravatar_hash(email)
    return f"https://secure.gravatar.com/{email_hash}"

@register.filter
def gravatar(email, size=20):
    """
    Returns an HTML image tag for the Gravatar of a given email,
    with the specified width and height.
    """
    url = gravatar_url(email, size)
    # Return a safe HTML snippet with the image element
    html = f'<img src="{url}" width="{size}" height="{size}" alt="Gravatar"></img>'
    return mark_safe(html)

@register.filter
def gravatar_no_hover(email, size=20):
    """
    Returns an HTML image tag for the Gravatar of a given email,
    with the specified width and height.
    """
    url = gravatar_url(email, size)
    # Return a safe HTML snippet with the image element
    html = f'<img src="{url}" width="{size}" height="{size}" alt="Gravatar" class="ignore"></img>'
    return mark_safe(html)

@register.filter
def gravatar_profile_data(email):
    """
    Retrieves the Gravatar profile JSON for a given email.
    It fetches data from https://gravatar.com/<HASH>.json, extracts the first entry,
    and returns it as a standardized dictionary for use in templates.
    If the email is None or if any error occurs, returns an empty dictionary.
    """
    if not email:
        return {}
    email_hash = gravatar_hash(email)
    url = f"https://gravatar.com/{email_hash}.json"
    try:
        response = requests.get(url, timeout=5)
        response.raise_for_status()
        data = response.json()
        # Gravatar's JSON response typically contains an "entry" list; we take the first entry.
        if "entry" in data and data["entry"]:
            return data["entry"][0]
        return {}
    except (requests.RequestException, ValueError):
        return {}
