import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import java.nio.ByteBuffer;
import java.nio.charset.CharacterCodingException;
import java.nio.charset.CodingErrorAction;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class LengthFrameDemo {
    private static final int MAX_FRAME = 64 * 1024;

    public static byte[] readFrame(InputStream input) throws IOException {
        int first = input.read();
        if (first == -1) return null;
        byte[] header = new byte[Integer.BYTES];
        header[0] = (byte) first;
        readExactly(input, header, 1, header.length - 1);
        int length = ByteBuffer.wrap(header).getInt();
        if (length < 0 || length > MAX_FRAME) throw new IOException("invalid length=" + length);
        byte[] body = new byte[length];
        readExactly(input, body, 0, length);
        return body;
    }

    private static void readExactly(InputStream input, byte[] target, int offset, int length) throws IOException {
        int completed = 0;
        while (completed < length) {
            int count = input.read(target, offset + completed, length - completed);
            if (count == -1) throw new EOFException("truncated frame");
            if (count == 0) throw new IOException("non-progressing input stream");
            completed += count;
        }
    }

    public static String decodeText(byte[] body) throws CharacterCodingException {
        return StandardCharsets.UTF_8.newDecoder()
                .onMalformedInput(CodingErrorAction.REPORT)
                .onUnmappableCharacter(CodingErrorAction.REPORT)
                .decode(ByteBuffer.wrap(body)).toString();
    }

    private static byte[] frames(byte[]... bodies) throws IOException {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        try (DataOutputStream output = new DataOutputStream(bytes)) {
            for (byte[] body : bodies) {
                if (body.length > MAX_FRAME) throw new IOException("body too large");
                output.writeInt(body.length);
                output.write(body);
            }
        }
        return bytes.toByteArray();
    }

    private static void rejects(byte[] bytes, Class<? extends IOException> expected) throws IOException {
        try {
            readFrame(new ByteArrayInputStream(bytes));
        } catch (IOException failure) {
            if (expected.isInstance(failure)) return;
            throw failure;
        }
        throw new IllegalStateException("invalid frame accepted");
    }

    public static void main(String[] args) throws Exception {
        byte[] text = "你好TCP".getBytes(StandardCharsets.UTF_8);
        byte[] maximum = new byte[MAX_FRAME];
        Arrays.fill(maximum, (byte) 7);
        byte[][] expected = {text, new byte[0], maximum};
        byte[] wire = frames(expected);
        for (int chunk : new int[]{1, 2, 3, 4, 997, wire.length}) {
            InputStream input = new ByteArrayInputStream(wire) {
                @Override
                public synchronized int read(byte[] target, int offset, int length) {
                    return super.read(target, offset, Math.min(length, chunk));
                }
            };
            for (byte[] body : expected) {
                if (!Arrays.equals(body, readFrame(input))) throw new IllegalStateException("content mismatch");
            }
            if (readFrame(input) != null) throw new IllegalStateException("expected clean EOF");
        }
        byte[] one = frames(text);
        for (int length = 1; length < one.length; length++) {
            rejects(Arrays.copyOf(one, length), EOFException.class);
        }
        rejects(ByteBuffer.allocate(4).putInt(-1).array(), IOException.class);
        rejects(ByteBuffer.allocate(4).putInt(MAX_FRAME + 1).array(), IOException.class);
        if (!decodeText(text).equals("你好TCP")) throw new IllegalStateException("text mismatch");
        try {
            decodeText(new byte[]{(byte) 0xc3, 0x28});
            throw new IllegalStateException("malformed UTF-8 accepted");
        } catch (CharacterCodingException expectedFailure) {
            System.out.println("strict UTF-8 rejection: PASS");
        }
        System.out.println("six chunk sizes, multiple frames, empty/max body, clean EOF: PASS");
        System.out.println("every truncated prefix, negative/oversize length: PASS");
    }
}
