"""
Privacy-preserving utilities for handling receipt data.
"""

from collections import Counter
from typing import Any, Dict, List

# Default list of keys to redact. This can be expanded.
# Using simple string matching for keys.
DEFAULT_REDACTION_KEYS = [
    "user_id",
    "ip_address",
    "email",
    "name",
    "token",
    "password",
    "secret",
    "payload", # Often contains sensitive data
]

REDACTION_PLACEHOLDER = "[REDACTED]"


def redact_context(
    context: Dict[str, Any],
    redaction_keys: List[str] = DEFAULT_REDACTION_KEYS,
) -> Dict[str, Any]:
    """
    Recursively redacts sensitive keys from a dictionary.

    Args:
        context: The dictionary to redact.
        redaction_keys: A list of keys to search for and redact.

    Returns:
        A new dictionary with sensitive values replaced.
    """
    if not isinstance(context, dict):
        return context

    clean_context = {}
    for key, value in context.items():
        if any(rk in key.lower() for rk in redaction_keys):
            clean_context[key] = REDACTION_PLACEHOLDER
        elif isinstance(value, dict):
            clean_context[key] = redact_context(value, redaction_keys)
        elif isinstance(value, list):
            clean_context[key] = [
                redact_context(item, redaction_keys) if isinstance(item, dict) else item
                for item in value
            ]
        else:
            clean_context[key] = value
            
    return clean_context


def seal_sensitive_payload(
    receipt: Any,
    payload: Dict[str, Any],
    label_prefix: str = "pii",
) -> None:
    """
    Seal sensitive payload data within a receipt.

    This is a placeholder implementation for privacy-preserving receipt storage.
    In production, this should implement proper encryption/sealing of sensitive data.

    Args:
        receipt: The receipt object to attach sealed data to.
        payload: The sensitive payload to seal.
        label_prefix: Prefix for labeling sealed data.
    """
    # For now, this is a no-op placeholder
    # Future implementation should:
    # 1. Encrypt sensitive payload with receipt-specific key
    # 2. Store encrypted data in receipt.sealed_data field
    # 3. Add appropriate metadata about sealing method
    pass


def seal_value(data: Any, label: str) -> Dict[str, Any]:
    """
    Seal a value for privacy-preserving storage.

    Returns a dictionary with sealed metadata indicating the value was redacted.
    In production, this should implement proper encryption/sealing.

    Args:
        data: The data to seal.
        label: Label for the sealed data.

    Returns:
        A dictionary representing the sealed value.
    """
    # Placeholder implementation - returns a sealed envelope
    # Future: implement actual encryption/sealing
    return {
        "sealed": True,
        "label": label,
        "placeholder": "[SEALED]",
    }


def accumulate_envelope_counts(container: Any, counter: Counter[str]) -> None:
    """
    Accumulate counts from privacy envelopes in a container.

    Traverses the container structure and counts privacy envelope types.

    Args:
        container: The container (dict, list, or object) to search for envelopes.
        counter: Counter to accumulate envelope type counts.
    """
    # Placeholder implementation - defensive no-op
    # Future: implement actual envelope traversal and counting
    if isinstance(container, dict):
        if container.get("sealed"):
            envelope_type = container.get("label", "unknown")
            counter[envelope_type] += 1
        # Recursively check nested structures
        for value in container.values():
            if isinstance(value, (dict, list)):
                accumulate_envelope_counts(value, counter)
    elif isinstance(container, list):
        for item in container:
            if isinstance(item, (dict, list)):
                accumulate_envelope_counts(item, counter)