"""Entropy calculation utilities for message format inference.

Provides Shannon entropy computation used across boundary detection
and field classification.
"""

from __future__ import annotations

import numpy as np
from numpy.typing import NDArray


def calculate_byte_entropy(messages: list[NDArray[np.uint8]], offset: int) -> float:
    """Calculate entropy at byte offset across messages.

    : Entropy calculation for boundary detection.

    Args:
        messages: List of message arrays
        offset: Byte offset to analyze

    Returns:
        Shannon entropy in bits
    """
    values = [msg[offset] for msg in messages]
    return float(calculate_entropy(np.array(values)))


def calculate_entropy(values: NDArray[np.int_ | np.uint8]) -> float:
    """Calculate Shannon entropy of values.

    Args:
        values: Array of values

    Returns:
        Entropy in bits
    """
    if len(values) == 0:
        return 0.0

    # Count frequencies
    _unique, counts = np.unique(values, return_counts=True)
    probabilities = counts / len(values)

    # Calculate Shannon entropy
    entropy = -np.sum(probabilities * np.log2(probabilities + 1e-10))
    return float(entropy)
