from __future__ import annotations

import logging
import random
from datetime import datetime, timezone
from email.utils import parsedate_to_datetime
from typing import Any, Dict, Optional


logger = logging.getLogger("its_ai")


def mask_api_key(value: Optional[str]) -> str:
    if not value:
        return "<none>"
    tail = value[-4:]
    return f"***{tail}"


def now_utc() -> datetime:
    return datetime.now(timezone.utc)


def compute_retry_delay(
    attempt_index: int,
    retry_after_header: Optional[str],
    base_delay: float = 0.5,
    max_delay: float = 8.0,
) -> float:
    if retry_after_header:
        try:
            # Retry-After: seconds or HTTP-date
            seconds = float(retry_after_header)
            return max(0.0, min(seconds, max_delay))
        except ValueError:
            try:
                dt = parsedate_to_datetime(retry_after_header)
                if dt.tzinfo is None:
                    dt = dt.replace(tzinfo=timezone.utc)
                delta = (dt - now_utc()).total_seconds()
                return max(0.0, min(delta, max_delay))
            except Exception:
                pass
    # Exponential backoff with jitter to prevent thundering herd
    delay = base_delay * (2 ** attempt_index) * (0.5 + random.random())
    return min(delay, max_delay)


def redact_payload(data: Dict[str, Any]) -> Dict[str, Any]:
    safe = dict(data)
    if "api_key" in safe and isinstance(safe["api_key"], str):
        safe["api_key"] = mask_api_key(safe["api_key"])  # type: ignore[assignment]
    return safe


