from urllib.parse import urlparse
from flask import request


def safe_redirect(fallback_url: str = "/", referrer_url: str = None) -> str:
    if referrer_url is None:
        referrer_url = request.referrer

    if not referrer_url:
        return fallback_url

    try:
        parsed_referrer = urlparse(referrer_url)

        if parsed_referrer.netloc and parsed_referrer.netloc == request.host:
            return referrer_url
    except Exception:
        pass

    return fallback_url
