import hashlib
from urllib.parse import urlparse

from django.conf import settings


def hash_ip(ip: str, salt: str = "") -> str:
    if not ip:
        return ""
    return hashlib.sha256(f"{salt}:{ip}".encode()).hexdigest()


def hash_visitor(ip: str, ua: str, salt: str = "") -> str:
    if not ip and not ua:
        return ""
    return hashlib.sha256(f"{salt}:{ip}:{ua}".encode()).hexdigest()


def client_ip(request) -> str:
    """Resolve the client IP, trusting X-Forwarded-For only for known proxy hops.

    XFF is attacker-controllable, so we only read it when TRUSTED_PROXY_COUNT > 0,
    and then take the entry N hops from the right (the address the closest trusted
    proxy observed). Anything else falls back to the un-spoofable REMOTE_ADDR.
    """
    remote = request.META.get("REMOTE_ADDR", "") or ""
    proxies = int(getattr(settings, "TRUSTED_PROXY_COUNT", 0) or 0)
    if proxies <= 0:
        return remote
    parts = [p.strip() for p in request.META.get("HTTP_X_FORWARDED_FOR", "").split(",") if p.strip()]
    if len(parts) >= proxies + 1:
        return parts[-1 - proxies]
    return remote


def referer_host(referer: str) -> str:
    if not referer:
        return ""
    try:
        return urlparse(referer).hostname or ""
    except Exception:
        return ""
