"""Utility functions for PHI field identification from registry metadata.

This module helps applications identify which fields the registry marks as PHI,
so applications can sanitize them BEFORE calling SDK methods. The SDK itself
performs NO PHI masking - that is the application's responsibility.

These functions extract PHI field names from registry API responses, allowing
applications to know which fields require sanitization.
"""

from typing import Dict, List, Any
import logging

logger = logging.getLogger(__name__)


def extract_phi_field_names(phi_fields: Dict[str, Any]) -> List[str]:
    """Extract PHI field names from registry response.

    The registry API returns phi_fields in two possible formats:
    1. Empty dict (no PHI): {}
    2. Nested structure with metadata: {"patient_id": {"criticality": "yes"}, ...}

    This function extracts field names so applications know which fields to sanitize
    before passing data to SDK methods.

    Args:
        phi_fields: PHI fields dict from registry API response

    Returns:
        List of PHI field names (keys from the dict)

    Example:
        >>> # Empty case
        >>> extract_phi_field_names({})
        []

        >>> # Nested case
        >>> phi_fields = {
        ...     "patient_id": {"criticality": "yes"},
        ...     "mrn": {"criticality": "yes"},
        ...     "ssn": {"criticality": "yes"}
        ... }
        >>> extract_phi_field_names(phi_fields)
        ['patient_id', 'mrn', 'ssn']
    """
    if not phi_fields:
        return []

    if not isinstance(phi_fields, dict):
        logger.warning(
            f"phi_fields is not a dict, got {type(phi_fields).__name__}. Returning empty list."
        )
        return []

    # Extract keys (field names), ignoring nested metadata
    return list(phi_fields.keys())


def get_phi_field_criticality(phi_fields: Dict[str, Any], field_name: str) -> str:
    """Get criticality level for a specific PHI field.

    Args:
        phi_fields: PHI fields dict from registry API response
        field_name: Name of the PHI field

    Returns:
        Criticality level ("yes", "no", "high", "medium", "low", or "unknown")

    Example:
        >>> phi_fields = {"patient_id": {"criticality": "yes"}}
        >>> get_phi_field_criticality(phi_fields, "patient_id")
        'yes'
        >>> get_phi_field_criticality(phi_fields, "nonexistent")
        'unknown'
    """
    if not phi_fields or not isinstance(phi_fields, dict):
        return "unknown"

    field_def = phi_fields.get(field_name)
    if not field_def or not isinstance(field_def, dict):
        return "unknown"

    return field_def.get("criticality", "unknown")
