"""PII redaction utilities for logging.

Provides utilities to redact sensitive information (emails, API keys) from log messages.
"""

from __future__ import annotations

import re

# Patterns for PII
_EMAIL_PATTERN = re.compile(r"\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b")
_API_KEY_PATTERN = re.compile(r"\b(sk-[a-zA-Z0-9]{32,})\b")  # OpenAI-style keys
_UUID_PATTERN = re.compile(r"\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b", re.IGNORECASE)


def redact_email(email: str) -> str:
    """Redact an email address for logging.

    Examples:
        user@example.com -> u***@example.com
        test@gmail.com -> t***@gmail.com
    """
    if "@" not in email:
        return email
    local, domain = email.split("@", 1)
    if len(local) <= 1:
        return f"{local[0]}***@{domain}"
    return f"{local[0]}***@{domain}"


def redact_api_key(key: str) -> str:
    """Redact an API key for logging.

    Examples:
        sk-abc123xyz789... -> sk-***xyz789 (first 3 + last 6)
    """
    if len(key) <= 10:
        return "***"
    return f"{key[:3]}***{key[-6:]}"


def redact_uuid(uuid_str: str) -> str:
    """Redact a UUID for logging.

    Examples:
        550e8400-e29b-41d4-a716-446655440000 -> 550e8400-****-****-****-************
    """
    parts = uuid_str.split("-")
    if len(parts) != 5:
        return uuid_str
    return f"{parts[0]}-****-****-****-************"


def redact_text(text: str) -> str:
    """Redact all PII from a text string.

    This is a convenience function that applies all redaction patterns.
    """
    # Redact API keys
    text = _API_KEY_PATTERN.sub(lambda m: redact_api_key(m.group(1)), text)
    # Redact emails
    text = _EMAIL_PATTERN.sub(lambda m: redact_email(m.group(0)), text)
    # Redact UUIDs (optional - may be needed for some use cases)
    # text = _UUID_PATTERN.sub(lambda m: redact_uuid(m.group(0)), text)
    return text


def safe_log_email(email: str) -> str:
    """Return a safely redacted email for logging.

    This is the primary function to use when logging emails.
    """
    return redact_email(email)


def safe_log_api_key(key: str) -> str:
    """Return a safely redacted API key for logging.

    This is the primary function to use when logging API keys.
    """
    return redact_api_key(key)
