#![deny(warnings)]
#![allow(dead_code)]
// [TSM.ID].[11031972] -- All Rights Reserved. Proprietary & Confidential.
//! xcu-quic -- QUIC Signal Protocol with Zero-Copy Schema
pub mod schema;
pub mod server;

/// QUIC packet header parser (RFC 9000 compatible)
#[derive(Debug, Clone, PartialEq)]
pub enum QuicPacketType {
    Initial,
    ZeroRtt,
    Handshake,
    Retry,
    Short,
}

/// Parse QUIC packet type from first byte (long header form)
pub fn parse_packet_type(first_byte: u8) -> QuicPacketType {
    if first_byte & 0x80 == 0 {
        return QuicPacketType::Short;
    }
    match (first_byte & 0x30) >> 4 {
        0x00 => QuicPacketType::Initial,
        0x01 => QuicPacketType::ZeroRtt,
        0x02 => QuicPacketType::Handshake,
        0x03 => QuicPacketType::Retry,
        _ => QuicPacketType::Short,
    }
}

/// Encode variable-length integer (QUIC VarInt, RFC 9000 Section 16)
pub fn encode_varint(value: u64) -> Vec<u8> {
    if value < 64 {
        vec![value as u8]
    } else if value < 16384 {
        let v = value as u16 | 0x4000;
        vec![(v >> 8) as u8, v as u8]
    } else if value < 1_073_741_824 {
        let v = value as u32 | 0x80000000;
        vec![(v >> 24) as u8, (v >> 16) as u8, (v >> 8) as u8, v as u8]
    } else {
        let v = value | 0xC000000000000000;
        v.to_be_bytes().to_vec()
    }
}

/// Decode variable-length integer from bytes
pub fn decode_varint(data: &[u8]) -> Option<(u64, usize)> {
    if data.is_empty() { return None; }
    let prefix = data[0] >> 6;
    let len = 1 << prefix;
    if data.len() < len { return None; }
    let mut value = (data[0] as u64) & 0x3F;
    for i in 1..len {
        value = (value << 8) | data[i] as u64;
    }
    Some((value, len))
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_packet_type_parsing() {
        assert_eq!(parse_packet_type(0xC0), QuicPacketType::Initial); // 1100_0000
        assert_eq!(parse_packet_type(0xD0), QuicPacketType::ZeroRtt); // 1101_0000
        assert_eq!(parse_packet_type(0xE0), QuicPacketType::Handshake); // 1110_0000
        assert_eq!(parse_packet_type(0xF0), QuicPacketType::Retry); // 1111_0000
        assert_eq!(parse_packet_type(0x40), QuicPacketType::Short); // short header
    }

    #[test]
    fn test_varint_roundtrip() {
        for val in [0u64, 63, 64, 16383, 16384, 1_000_000] {
            let encoded = encode_varint(val);
            let (decoded, _len) = decode_varint(&encoded).expect("decode");
            assert_eq!(decoded, val, "Failed roundtrip for {val}");
        }
    }

    #[test]
    fn test_varint_lengths() {
        assert_eq!(encode_varint(0).len(), 1);
        assert_eq!(encode_varint(63).len(), 1);
        assert_eq!(encode_varint(64).len(), 2);
        assert_eq!(encode_varint(16383).len(), 2);
        assert_eq!(encode_varint(16384).len(), 4);
    }
}
