# #region SupersetContextExtractorPII [C:3] [TYPE Module] [SEMANTICS superset, dataset, assistant, review]
# @LAYER Infrastructure
# @BRIEF PII redaction helpers for assistant-facing dataset-review context — mask emails, UUIDs, long digit strings, and mixed identifiers.
# #endregion SupersetContextExtractorPII

# #region _pii_imports [TYPE Block]
from copy import deepcopy
import re
from typing import Any

# #endregion _pii_imports

_EMAIL_PATTERN = re.compile(
    r"(?P<local>[A-Za-z0-9._%+-]+)@(?P<domain>[A-Za-z0-9.-]+\.[A-Za-z]{2,})"
)
_UUID_PATTERN = re.compile(
    r"\b[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}\b"
)
_LONG_DIGIT_PATTERN = re.compile(r"\b\d{6,}\b")
_MIXED_IDENTIFIER_PATTERN = re.compile(
    r"\b(?=[A-Za-z0-9_-]{10,}\b)(?=.*[A-Za-z])(?=.*\d)[A-Za-z0-9_-]+\b"
)


# #region mask_pii_value [C:2] [TYPE Function]
# @BRIEF Redact likely sensitive identifiers while preserving structural hints for assistant-facing dataset-review context.
def mask_pii_value(value: Any) -> tuple[Any, bool]:
    if isinstance(value, str):
        return _mask_sensitive_text(value)
    if isinstance(value, list):
        masked_any = False
        masked_list: list[Any] = []
        for item in value:
            masked_item, item_masked = mask_pii_value(item)
            masked_list.append(masked_item)
            masked_any = masked_any or item_masked
        return masked_list, masked_any
    if isinstance(value, dict):
        masked_any = False
        masked_dict: dict[str, Any] = {}
        for key, item in value.items():
            masked_item, item_masked = mask_pii_value(item)
            masked_dict[key] = masked_item
            masked_any = masked_any or item_masked
        return masked_dict, masked_any
    return value, False


# #endregion mask_pii_value


# #region sanitize_imported_filter_for_assistant [C:2] [TYPE Function]
# @BRIEF Build assistant-safe imported-filter payload with raw-value redaction metadata when sensitive tokens are detected.
def sanitize_imported_filter_for_assistant(
    filter_payload: dict[str, Any],
) -> dict[str, Any]:
    sanitized = deepcopy(filter_payload)
    masked_raw_value, was_masked = mask_pii_value(filter_payload.get("raw_value"))
    sanitized["raw_value"] = masked_raw_value
    sanitized["raw_value_masked"] = bool(
        filter_payload.get("raw_value_masked", False) or was_masked
    )
    return sanitized


# #endregion sanitize_imported_filter_for_assistant


# #region _mask_sensitive_text [C:2] [TYPE Function]
# @BRIEF Redact likely PII substrings from one string while preserving non-sensitive delimiters and token shape.
def _mask_sensitive_text(value: str) -> tuple[str, bool]:
    masked = value
    masked_any = False

    def _replace_email(match: re.Match[str]) -> str:
        nonlocal masked_any
        masked_any = True
        domain = match.group("domain")
        return f"***@{domain}"

    def _replace_uuid(match: re.Match[str]) -> str:
        nonlocal masked_any
        masked_any = True
        token = match.group(0)
        return "********-****-****-****-" + token[-12:]

    def _replace_long_digits(match: re.Match[str]) -> str:
        nonlocal masked_any
        masked_any = True
        token = match.group(0)
        return "*" * max(len(token) - 2, 1) + token[-2:]

    def _replace_mixed_identifier(match: re.Match[str]) -> str:
        nonlocal masked_any
        token = match.group(0)
        if token.isupper() and len(token) <= 5:
            return token
        masked_any = True
        return token[:2] + "***" + token[-2:]

    masked = _EMAIL_PATTERN.sub(_replace_email, masked)
    masked = _UUID_PATTERN.sub(_replace_uuid, masked)
    masked = _LONG_DIGIT_PATTERN.sub(_replace_long_digits, masked)
    masked = _MIXED_IDENTIFIER_PATTERN.sub(_replace_mixed_identifier, masked)
    return masked, masked_any


# #endregion _mask_sensitive_text
