from __future__ import annotations

from typing import Any, Optional

from chatsee.redaction.engine import redact_payload_sync
from chatsee.redaction.loader import load_redaction_rules_sync
from chatsee.env import resolve_api_base_url


def redact(
    payload: Any,
    *,
    api_base_url: Optional[str] = None,
    classifiers_url: Optional[str] = None,
    fields_to_redact: Any = "*",
    cache_ttl_seconds: int = 300,
    timeout_seconds: float = 5.0,
    verify_ssl: bool = True,
) -> Any:
    """
    Redact an arbitrary payload using classifiers fetched from the Chatsee redaction API.
    This does not send anything to Chatsee.

    Provide either:
    - api_base_url ("qa" | "demo" | "gcp" or full URL), or
    - classifiers_url (full endpoint)
    """
    # Requirement: classifiers are always fetched from QA by default.
    qa_base = resolve_api_base_url("qa").rstrip("/")
    url = classifiers_url or f"{qa_base}/v1/redaction/fetch-classifiers"
    if not url:
        raise ValueError("redact() requires classifiers_url or api_base_url")

    rules = load_redaction_rules_sync(
        classifiers_url=url,
        cache_ttl_seconds=int(cache_ttl_seconds),
        timeout_seconds=float(timeout_seconds),
        verify_ssl=verify_ssl,
    )
    if not rules:
        return payload
    return redact_payload_sync(payload, rules, fields_to_redact=fields_to_redact)

