package com.foxx.androidcast.network.transport.fec;

/*********************************************************************
 * ReedSolomonFecTest.java
 * Created at: Sun 17 May 2026 22:49:49 +0200
 * Updated at: Wed 20 May 2026 15:17:13 +0200 by Anton Afanasyeu <a.afanasieff@gmail.com>
 * Commit: 5d8e82d2e60a21fff3138d2a394ee4e8b4c6dcb8
 * class ReedSolomonFecTest
 * Contributors:
 *    - Anton Afanasyeu <a.afanasieff@gmail.com> (2 commits, 66 lines)
 *    - Cursor Agent (project assistant)
 * Digest: SHA256	17746d64c23ac6a37735537ac523e6ec5fa3074a4509f73268156aa7db40d193
**********************************************************************/
import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;

import org.junit.Test;

public class ReedSolomonFecTest {
    @Test
    public void encodeDecode_fec34_recoversOneLoss() {
        ReedSolomonFec fec = new ReedSolomonFec(4, 3);
        byte[] payload = "android-cast-fec-test-payload-12345".getBytes();
        byte[][] shards = fec.encode(payload);
        shards[2] = null;
        byte[] recovered = fec.decode(shards, payload.length);
        assertNotNull(recovered);
        assertArrayEquals(payload, recovered);
    }

    @Test
    public void decode_insufficientShards_returnsNull() {
        ReedSolomonFec fec = new ReedSolomonFec(4, 3);
        byte[] payload = new byte[] {1, 2, 3, 4, 5};
        byte[][] shards = fec.encode(payload);
        for (int i = 0; i < 5; i++) {
            shards[i] = null;
        }
        assertNull(fec.decode(shards, payload.length));
    }

    @Test
    public void isProtected_rejectsHelloLikeFalsePositive() {
        byte[] fake = new byte[200];
        fake[0] = 'A';
        fake[1] = 'C';
        fake[2] = 'P';
        fake[3] = 'F';
        fake[4] = ProtectionEnvelope.VERSION;
        fake[5] = ProtectionEnvelope.MODE_FEC_34;
        fake[9] = 4;
        fake[10] = 3;
        fake[11] = 22;
        assertFalse(ProtectionEnvelope.isProtected(fake));
    }

    @Test
    public void protectionEnvelope_roundTrip() throws Exception {
        byte[] payload = new byte[512];
        for (int i = 0; i < payload.length; i++) {
            payload[i] = (byte) (i & 0xFF);
        }
        byte[] wire = ProtectionEnvelope.encode(ProtectionEnvelope.MODE_FEC_34, 4, 3, payload);
        ProtectionEnvelope.Decoded decoded = ProtectionEnvelope.tryDecode(wire);
        assertNotNull(decoded);
        assertArrayEquals(payload, decoded.payload);
    }
}
