from __future__ import annotations

import os
from typing import Any, Dict, List, Optional, Tuple

from .asgi import UltimateProtectorMiddleware


def _parse_list(raw: str | None) -> Optional[List[str]]:
    if not raw:
        return None
    s = str(raw).strip()
    if not s:
        return None
    parts: List[str] = []
    for chunk in s.replace(",", "\n").splitlines():
        p = chunk.strip()
        if p:
            parts.append(p)
    return parts or None


def config_from_env(prefix: str = "UP_") -> Dict[str, Any]:
    license_key = str(os.getenv(prefix + "LICENSE_KEY", "")).strip()
    api_url = str(os.getenv(prefix + "API_URL", "")).strip()

    if not license_key or not api_url:
        return {}

    cfg: Dict[str, Any] = {
        "license_key": license_key,
        "api_url": api_url,
    }

    if os.getenv(prefix + "SYNC_INTERVAL_SECONDS"):
        cfg["sync_interval_seconds"] = int(os.getenv(prefix + "SYNC_INTERVAL_SECONDS") or "60")
    if os.getenv(prefix + "ALLOW_SAMPLE_RATE"):
        cfg["allow_sample_rate"] = float(os.getenv(prefix + "ALLOW_SAMPLE_RATE") or "0.01")

    only_paths = _parse_list(os.getenv(prefix + "ONLY_PATHS"))
    except_paths = _parse_list(os.getenv(prefix + "EXCEPT_PATHS"))
    only_regex = os.getenv(prefix + "ONLY_REGEX")
    if only_paths:
        cfg["only_paths"] = only_paths
    if except_paths:
        cfg["except_paths"] = except_paths
    if only_regex:
        cfg["only_regex"] = str(only_regex)

    return cfg


def wrap_asgi_app(app, *, prefix: str = "UP_"):
    """Return ASGI app wrapped with UltimateProtectorMiddleware if env is configured.

    Intended for zero-code installs via a tiny import in your app factory (or sitecustomize).
    """

    if os.getenv(prefix + "AGENT_DISABLE"):
        return app

    cfg = config_from_env(prefix=prefix)
    if not cfg:
        return app

    return UltimateProtectorMiddleware(app, **cfg)
