"""Utility functions for PHI field handling.

This module provides helper functions for working with PHI field definitions
from the registry API, which can have different structures.
"""

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 just the field names for masking purposes.

    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")
