from __future__ import annotations

import httpx
from typing import Optional, Dict, Union
import os
from agentui.config import build_httpx_proxies, get_tls_verify, is_verify_explicit


def _mask_proxy(url: str) -> str:
    """Маскируем часть с логином/паролем в URL прокси, чтобы не утекла в логи."""
    try:
        if "://" in url and "@" in url:
            prefix, rest = url.split("://", 1)
            auth, host = rest.split("@", 1)
            return f"{prefix}://***@{host}"
        return url
    except Exception:
        return "<masked>"


def build_client(timeout: float = 60.0) -> httpx.AsyncClient:
    proxies: Optional[Dict[str, str]] = build_httpx_proxies()
    verify: Union[bool, str] = get_tls_verify()

    explicit = is_verify_explicit()
    # По умолчанию при наличии прокси отключаем проверку сертификатов,
    # но не трогаем, если пользователь явно задал verify или CA.
    if proxies and (verify is True) and (not explicit):
        verify = False

    if os.getenv("AGENTUI_DEBUG", "").lower() in ("1", "true", "on", "yes"):
        masked = {k: _mask_proxy(v) for k, v in (proxies or {}).items()}
        print("[agentui.http_client] proxies=", masked, " verify=", verify)

    # httpx сам понимает схемы socks://, socks5:// при установленном extras [socks]
    try:
        client = httpx.AsyncClient(
            timeout=timeout,
            proxies=proxies,
            follow_redirects=True,
            verify=verify,
        )
    except TypeError:
        if proxies:
            try:
                masked = {k: _mask_proxy(v) for k, v in proxies.items()}
            except Exception:
                masked = proxies
            print(f"[agentui.http_client] WARNING: proxies not supported in httpx.AsyncClient, skipping proxies={masked}")
        client = httpx.AsyncClient(
            timeout=timeout,
            follow_redirects=True,
            verify=verify,
        )
    return client


