import argparse
import math
import numpy as np


def parse_args():
    p = argparse.ArgumentParser(
        description="Parallel high-rate fractal-static data experiment"
    )
    p.add_argument("--fs", type=int, default=192000)
    p.add_argument("--duration", type=float, default=2.0)
    p.add_argument("--channels", type=int, default=96)
    p.add_argument("--alphabet", type=int, default=16)
    p.add_argument("--chips", type=int, default=16)
    p.add_argument("--samples-per-chip", type=int, default=64)
    p.add_argument("--seed", type=int, default=17)
    p.add_argument("--gain", type=float, default=0.70,
                   help="Amplitude modulation depth, 0..0.95")
    p.add_argument("--noise", type=float, default=0.0,
                   help="Additional additive white noise power ratio")
    p.add_argument("--report-every", type=int, default=0)
    return p.parse_args()


def hadamard(n):
    """Sylvester Hadamard matrix; n must be a power of two."""
    h = np.array([[1.0]])
    while h.shape[0] < n:
        h = np.block([[h, h], [h, -h]])
    return h


def make_codebook(alphabet, chips):
    if chips & (chips - 1):
        raise ValueError("--chips must be a power of two")
    if alphabet < 2 or alphabet > chips:
        raise ValueError("--alphabet must be between 2 and --chips")
    # Discard the all-ones row: it carries no modulation contrast.
    h = hadamard(chips)[1:alphabet + 1]
    if len(h) < alphabet:
        raise ValueError("Insufficient non-DC codewords")
    return h[:alphabet]


def make_payload(rng, channels, symbols, alphabet):
    return rng.integers(0, alphabet, size=(channels, symbols), dtype=np.uint16)


def encode_channel(payload, codebook, samples_per_chip, gain, rng, noise):
    """
    Encode one independent channel:
      x[n] = carrier[n] * (1 + gain * codeword_chip)
    The codeword is held for samples_per_chip samples.
    """
    channels, symbols = payload.shape
    chips = codebook.shape[1]
    samples_per_symbol = chips * samples_per_chip
    n = symbols * samples_per_symbol

    chip_codes = codebook[payload]             # C x S x chips
    envelope = 1.0 + gain * chip_codes
    envelope = np.repeat(envelope, samples_per_chip, axis=2)
    carrier = rng.standard_normal((channels, n), dtype=np.float32)
    signal = carrier * envelope.astype(np.float32)

    if noise > 0:
        signal += (
            rng.standard_normal(signal.shape, dtype=np.float32)
            * np.float32(math.sqrt(noise))
        )
    return signal


def decode_channel(signal, codebook, samples_per_chip, gain):
    """
    Estimate chip energy, remove common carrier scale, then correlate
    log-energy against the known amplitude codewords.
    """
    channels, n = signal.shape
    chips = codebook.shape[1]
    samples_per_symbol = chips * samples_per_chip
    symbols = n // samples_per_symbol

    usable = signal[:, :symbols * samples_per_symbol]
    blocks = usable.reshape(
        channels, symbols, chips, samples_per_chip
    )
    energy = np.mean(blocks * blocks, axis=3)
    log_energy = np.log(np.maximum(energy, 1e-20))

    # Remove per-symbol carrier gain and normalize chip profile.
    log_energy -= np.mean(log_energy, axis=2, keepdims=True)
    norms = np.linalg.norm(log_energy, axis=2, keepdims=True)
    features = log_energy / np.maximum(norms, 1e-20)

    # Expected log-power templates for each amplitude codeword.
    amp = 1.0 + gain * codebook
    templates = np.log(amp * amp)
    templates -= templates.mean(axis=1, keepdims=True)
    templates /= np.maximum(
        np.linalg.norm(templates, axis=1, keepdims=True), 1e-20
    )

    # C x S x A
    scores = np.einsum("csk,ak->csa", features, templates)
    return np.argmax(scores, axis=2), scores


def bits_per_symbol(alphabet):
    return int(math.floor(math.log2(alphabet)))


def payload_bits(payload, bits):
    # Fixed-width binary representation, MSB first.
    shifts = np.arange(bits - 1, -1, -1, dtype=np.uint16)
    return ((payload[..., None] >> shifts) & 1).astype(np.uint8)


def summarize(true_payload, decoded, fs, chips, samples_per_chip, alphabet):
    bits = bits_per_symbol(alphabet)
    true_bits = payload_bits(true_payload, bits)
    decoded_bits = payload_bits(decoded, bits)
    bit_errors = int(np.count_nonzero(true_bits != decoded_bits))
    total_bits = int(true_bits.size)
    symbol_errors = int(np.count_nonzero(true_payload != decoded))
    total_symbols = int(true_payload.size)
    symbol_rate = fs / (chips * samples_per_chip)
    raw_rate = symbol_rate * bits * true_payload.shape[0]
    return {
        "bit_errors": bit_errors,
        "total_bits": total_bits,
        "ber": bit_errors / max(total_bits, 1),
        "symbol_errors": symbol_errors,
        "total_symbols": total_symbols,
        "ser": symbol_errors / max(total_symbols, 1),
        "symbol_rate": symbol_rate,
        "raw_rate": raw_rate,
        "delivered_rate": raw_rate * (1.0 - bit_errors / max(total_bits, 1)),
    }


def main():
    a = parse_args()
    if a.fs <= 0 or a.duration <= 0 or a.channels < 1:
        raise ValueError("fs, duration, and channels must be positive")
    if a.samples_per_chip < 2:
        raise ValueError("--samples-per-chip must be >= 2")
    if not 0.0 < a.gain < 1.0:
        raise ValueError("--gain must be between 0 and 1")
    if a.noise < 0:
        raise ValueError("--noise cannot be negative")

    rng = np.random.default_rng(a.seed)
    codebook = make_codebook(a.alphabet, a.chips)
    bits = bits_per_symbol(a.alphabet)
    samples_per_symbol = a.chips * a.samples_per_chip
    symbol_rate = a.fs / samples_per_symbol
    symbols = max(1, int(a.duration * symbol_rate))
    actual_duration = symbols / symbol_rate

    payload = make_payload(rng, a.channels, symbols, a.alphabet)

    # Encode/decode channels in batches to bound RAM use.
    decoded = np.empty_like(payload)
    batch_size = max(1, min(a.channels, 16))
    for first in range(0, a.channels, batch_size):
        last = min(first + batch_size, a.channels)
        block_payload = payload[first:last]
        encoded = encode_channel(
            block_payload, codebook, a.samples_per_chip,
            a.gain, rng, a.noise
        )
        block_decoded, _ = decode_channel(
            encoded, codebook, a.samples_per_chip, a.gain
        )
        decoded[first:last] = block_decoded
        if a.report_every and (first // batch_size) % a.report_every == 0:
            print(f"Processed channels {first + 1}–{last}/{a.channels}")

    result = summarize(
        payload, decoded, a.fs, a.chips,
        a.samples_per_chip, a.alphabet
    )

    print()
    print("=" * 72)
    print("STATIC MOD V4 — PARALLEL HIGH-RATE DATA")
    print("=" * 72)
    print(f"Sampling rate:                 {a.fs:,} samples/s per channel")
    print(f"Parallel channels:             {a.channels}")
    print(f"Code alphabet:                 {a.alphabet} symbols")
    print(f"Bits per symbol:               {bits}")
    print(f"Chips per symbol:              {a.chips}")
    print(f"Samples per chip:              {a.samples_per_chip}")
    print(f"Samples per symbol:            {samples_per_symbol:,}")
    print(f"Symbol rate per channel:       {symbol_rate:,.2f} symbols/s")
    print(f"Symbols transmitted/channel:   {symbols:,}")
    print(f"Payload duration:              {actual_duration:.4f} s")
    print()
    print("[DATA RATE]")
    print(f"Raw aggregate rate:            {result['raw_rate']:,.0f} bit/s")
    print(f"Raw aggregate rate:            {result['raw_rate']/1e6:.4f} Mbit/s")
    print(f"Measured delivered rate:       {result['delivered_rate']:,.0f} bit/s")
    print(f"Measured delivered rate:       {result['delivered_rate']/1e6:.4f} Mbit/s")
    print()
    print("[DECODE]")
    print(f"Symbol errors:                 {result['symbol_errors']:,}/{result['total_symbols']:,}")
    print(f"Symbol error rate:             {result['ser']:.6f}")
    print(f"Bit errors:                    {result['bit_errors']:,}/{result['total_bits']:,}")
    print(f"Bit error rate:                {result['ber']:.8f}")
    print()
    print("[MODEL]")
    print(f"AM depth:                      {a.gain:.3f}")
    print(f"Additional noise power ratio:  {a.noise:.6g}")
    print(f"Seed:                          {a.seed}")
    print()
    print("Rate is a simulated raw payload rate, not a measured RF link rate.")
    print("The channels are independent parallel baseband streams in this test.")
    print("A physical implementation still needs channel filters, synchronization,")
    print("transmit/receive hardware, and an RF/link budget.")
    print("=" * 72)


if __name__ == "__main__":
    main()