from dataclasses import dataclass
import os
from pathlib import Path

from .http_client import HttpClient
from .settings import AppConfig


@dataclass
class AppContext:
    config: AppConfig
    http: HttpClient
    debug: bool = False
    debug_dir: Path = Path(".adc_debug")


def build_context(config_path: str, proxy_override: str | None = None, debug: bool = False) -> AppContext:
    conf = AppConfig.from_path(config_path)
    proxy_from_config, timeout, retry = conf.proxy()

    if proxy_override is not None:
        proxy = proxy_override.strip()
    else:
        proxy = _env_https_proxy() or proxy_from_config

    http = HttpClient(proxy=proxy, timeout=timeout, retry=retry)
    ctx = AppContext(config=conf, http=http, debug=debug)
    if ctx.debug:
        ctx.debug_dir.mkdir(parents=True, exist_ok=True)
    return ctx


def _env_https_proxy() -> str | None:
    value = os.getenv("https_proxy") or os.getenv("HTTPS_PROXY")
    if value is None:
        return None
    value = value.strip()
    return value if value else None
