"""
DMPPM (differential-mode pulse-position modulation) protocol.

The interval between consecutive pulses carries one symbol:
    interval_k = t_min + (s_k + 0.5) * t_slot,   s_k in [0, 2^BPP)
The receiver only needs pulse-to-pulse differences, so no frame clock is shared.

This file is the protocol definition. Both the independent system model and the
integrated block-level model use it, as an encoder and decoder must agree on the format.
"""
import numpy as np
from .params import DMPPMParams


def gray_encode(n: np.ndarray) -> np.ndarray:
    return n ^ (n >> 1)


def gray_decode(g: np.ndarray) -> np.ndarray:
    n = np.array(g, dtype=np.int64, copy=True)
    mask = n >> 1
    while np.any(mask):
        n ^= mask
        mask >>= 1
    return n


def bits_to_symbols(bits: np.ndarray, p: DMPPMParams) -> np.ndarray:
    k = p.bits_per_pulse
    bits = np.asarray(bits, dtype=np.int64)
    if bits.size % k:
        raise ValueError(f"bit count must be a multiple of {k}")
    w = 1 << np.arange(k - 1, -1, -1)
    sym = bits.reshape(-1, k) @ w
    # Gray: slot index is chosen so neighbouring slots differ by one bit
    return gray_decode(sym) if p.gray else sym


def symbols_to_bits(sym: np.ndarray, p: DMPPMParams) -> np.ndarray:
    k = p.bits_per_pulse
    sym = np.asarray(sym, dtype=np.int64)
    val = gray_encode(sym) if p.gray else sym
    return ((val[:, None] >> np.arange(k - 1, -1, -1)) & 1).astype(np.int8).ravel()


def symbols_to_intervals(sym: np.ndarray, p: DMPPMParams) -> np.ndarray:
    g = getattr(p, "grid", 0.0)
    if g:   # slot grid (proposal P2): every interval is a whole number of DTC steps
        n = p.slot_steps
        return (np.round(p.t_min / g) + np.asarray(sym) * n + n // 2) * g
    return p.t_min + (np.asarray(sym) + 0.5) * p.t_slot


def intervals_to_symbols(dt: np.ndarray, p: DMPPMParams) -> np.ndarray:
    s = np.floor((np.asarray(dt) - p.t_min) / p.t_slot).astype(np.int64)
    return np.clip(s, 0, p.n_slots - 1)


def pulse_times(sym: np.ndarray, p: DMPPMParams, t0: float = 0.0) -> np.ndarray:
    """Absolute pulse times: a reference pulse at t0, then one pulse per symbol."""
    return t0 + np.concatenate([[0.0], np.cumsum(symbols_to_intervals(sym, p))])
