from __future__ import annotations

import os
import urllib.parse
import urllib.request
from typing import Callable

DEFAULT_CDN_PROXY_HOSTS = ("app-static.com",)

HttpOpener = Callable[..., object]


def resolve_feimao_cdn_proxy(
    connectivity: dict | None = None,
    *,
    feimao_cfg: dict | None = None,
) -> str | None:
    """解析飞猫 CDN 出站代理（仅用于 upload CDN，不走 fmpapi）。"""
    connectivity = connectivity or {}
    feimao_cfg = feimao_cfg or {}
    raw = connectivity.get("cdn_proxy")
    if raw is None:
        raw = feimao_cfg.get("cdn_proxy")
    if raw is None or raw == "":
        return None
    if str(raw).lower() in ("auto", "env"):
        return os.environ.get("FEIMAO_CDN_PROXY") or os.environ.get("HTTPS_PROXY") or os.environ.get("HTTP_PROXY")
    return str(raw).strip() or None


def resolve_feimao_upload_timeouts(
    connectivity: dict | None = None,
) -> tuple[float, float]:
    """返回 (cdn_timeout_seconds, upload_progress_wait_seconds)。"""
    connectivity = connectivity or {}
    cdn_timeout = float(connectivity.get("upload_timeout_seconds", 600))
    progress_wait = float(connectivity.get("upload_progress_wait_seconds", cdn_timeout))
    return max(cdn_timeout, 1.0), max(progress_wait, 1.0)


def build_feimao_http_opener(
    *,
    cdn_proxy: str | None = None,
    cdn_proxy_hosts: tuple[str, ...] | list[str] | None = None,
) -> HttpOpener:
    """fmpapi 直连；匹配 cdn_proxy_hosts 的 URL 走 cdn_proxy。"""
    hosts = tuple(cdn_proxy_hosts or DEFAULT_CDN_PROXY_HOSTS)
    proxy_url = (cdn_proxy or "").strip() or None
    proxied: urllib.request.OpenerDirector | None = None
    if proxy_url:
        handler = urllib.request.ProxyHandler({"http": proxy_url, "https": proxy_url})
        proxied = urllib.request.build_opener(handler)

    def _host(url: str) -> str:
        return urllib.parse.urlparse(url).netloc.lower()

    def _use_proxy(url: str) -> bool:
        if not proxied:
            return False
        host = _host(url)
        return any(marker.lower() in host for marker in hosts)

    def open(url_or_request: urllib.request.Request | str, *args: object, **kwargs: object) -> object:
        if isinstance(url_or_request, urllib.request.Request):
            url = url_or_request.full_url
            req = url_or_request
        else:
            url = str(url_or_request)
            req = url_or_request
        if _use_proxy(url):
            return proxied.open(req, *args, **kwargs)
        return urllib.request.urlopen(req, *args, **kwargs)

    return open


def feimao_connectivity_options(
    config: dict | None = None,
    *,
    feimao_cfg: dict | None = None,
) -> dict[str, object]:
    """从 tier connectivity + providers 解析飞猫 upload 超时与 CDN 代理。"""
    config = config or {}
    feimao_cfg = feimao_cfg or {}
    tier_feimao = ((config.get("storage") or {}).get("tier") or {}).get("feimao") or {}
    conn = tier_feimao.get("connectivity") or {}
    cdn_proxy = resolve_feimao_cdn_proxy(conn, feimao_cfg=feimao_cfg)
    cdn_timeout, progress_wait = resolve_feimao_upload_timeouts(conn)
    hosts = conn.get("cdn_proxy_hosts") or feimao_cfg.get("cdn_proxy_hosts")
    http_opener = (
        build_feimao_http_opener(cdn_proxy=cdn_proxy, cdn_proxy_hosts=hosts)
        if cdn_proxy
        else None
    )
    return {
        "cdn_timeout": cdn_timeout,
        "upload_progress_wait": progress_wait,
        "http_opener": http_opener,
    }
