"""
Base utilities for MedTDA.

This module provides common validation functions used across the package.
"""

import numpy as np


def validate_barcode(barcode):
    """
    Validate a persistence barcode/diagram.
    
    Parameters
    ----------
    barcode : numpy.ndarray
        Barcode to validate (n x 2 array).
        
    Raises
    ------
    ValueError
        If barcode format is invalid.
        
    Returns
    -------
    numpy.ndarray
        Validated barcode.
    """
    if barcode is None or (isinstance(barcode, np.ndarray) and barcode.size == 0):
        return np.empty((0, 2))

    barcode = np.asarray(barcode)

    if barcode.ndim != 2:
        raise ValueError(f"Barcode must be 2D array. Got {barcode.ndim}D array.")

    if barcode.shape[1] != 2:
        raise ValueError(
            f"Barcode must have 2 columns (birth, death). Got {barcode.shape[1]} columns."
        )

    # Check for valid birth-death relationships
    if barcode.shape[0] > 0:
        if np.any(barcode[:, 1] < barcode[:, 0]):
            raise ValueError("All death values must be >= birth values in barcode.")

    return barcode


def get_background_value(image_array, normalize=False):
    """
    Determine appropriate background value based on image properties.
    
    Parameters
    ----------
    image_array : numpy.ndarray
        Input image array.
    normalize : bool, default=False
        Whether the image will be normalized.
        
    Returns
    -------
    float
        Appropriate background value.
        
    Notes
    -----
    Default background values:
    - If normalized: -1
    - If 2D: 0
    - If 3D/4D: -3000 (typical for CT scans)
    """
    if normalize:
        return -1

    if image_array.ndim == 2:
        return 0
    else:  # 3D or 4D
        return -3000
