"""PII tag set and redaction functions.

When ``DICOM_MCP_PII_FILTER`` is enabled (via environment variable),
patient-identifying tags are replaced with ``[REDACTED]`` in tool output.
"""

from typing import Any, Tuple

from dicom_mcp.constants import COMMON_TAGS

# The set of DICOM tags considered PII (patient tags only).
PII_TAGS: frozenset[Tuple[int, int]] = frozenset(COMMON_TAGS["patient_info"])

PII_REDACTED_VALUE = "[REDACTED]"


def is_pii_tag(tag_tuple: Tuple[int, int]) -> bool:
    """Return True if *tag_tuple* is a patient-identifying tag."""
    return tag_tuple in PII_TAGS


def redact_if_pii(tag_tuple: Tuple[int, int], value: Any) -> Any:
    """Return ``[REDACTED]`` when PII filtering is active and the tag is PII.

    The function checks the runtime config on every call so that
    ``importlib.reload(dicom_mcp.config)`` toggles behaviour in tests.
    """
    from dicom_mcp.config import PII_FILTER_ENABLED

    if PII_FILTER_ENABLED and is_pii_tag(tag_tuple):
        return PII_REDACTED_VALUE
    return value
