from __future__ import annotations

import urllib.parse
import urllib.request
from typing import Any, Callable

HttpOpener = Callable[..., Any]

_STRIP_AUTH_OPENER: urllib.request.OpenerDirector | None = None


def build_strip_auth_redirect_opener() -> urllib.request.OpenerDirector:
    """跨域 redirect 时去掉 Authorization，避免 CDN 返回 401（OneDrive / Google Drive 下载）。"""

    class _StripAuthOnCrossHostRedirect(urllib.request.HTTPRedirectHandler):
        def redirect_request(self, req, fp, code, msg, headers, newurl):
            redirected = super().redirect_request(req, fp, code, msg, headers, newurl)
            if redirected is None:
                return None
            old_host = urllib.parse.urlparse(req.full_url).netloc
            new_host = urllib.parse.urlparse(newurl).netloc
            if old_host == new_host:
                return redirected
            clean_headers = {
                key: value for key, value in redirected.header_items() if key.lower() != "authorization"
            }
            return urllib.request.Request(
                newurl,
                data=getattr(redirected, "data", None),
                headers=clean_headers,
                method=redirected.get_method(),
            )

    return urllib.request.build_opener(_StripAuthOnCrossHostRedirect())


def default_strip_auth_opener() -> urllib.request.OpenerDirector:
    global _STRIP_AUTH_OPENER
    if _STRIP_AUTH_OPENER is None:
        _STRIP_AUTH_OPENER = build_strip_auth_redirect_opener()
    return _STRIP_AUTH_OPENER


def open_with_strip_auth_redirect(req: urllib.request.Request, *, timeout: float) -> Any:
    return default_strip_auth_opener().open(req, timeout=timeout)
