/*
 * clickhouse-native-rs — Asynchronous ClickHouse client for Rust over the native TCP protocol
 * Copyright (c) 2026 Alexander Panasenko
 *
 * Contact: alex@prod.codes
 * Author: https://prod.codes/about/
 * Project: https://github.com/alex09x/clickhouse-native-rs
 * SPDX-License-Identifier: MIT
 */

//! A Data, Totals or Extremes packet read as its bytes arrive. What has come
//! is kept between reads: the frames already decompressed and how far the
//! walk over the block got. The block is parsed once, when it is whole, and
//! every frame is decompressed once (#7).

use std::io::{self, Cursor};

use chrono_tz::Tz;

use crate::{
    binary::ReadEx,
    errors::{Error, Result},
    types::{
        block::{
            compression::{decompress_frame, frame_len, FRAME_HEAD_SIZE},
            Block,
        },
        column::measure::{BlockWalk, Measure},
    },
};

/// The most the frame buffers keep between blocks: frames the server writes
/// (`max_compress_block_size`, 1 MiB by default) fit.
const RETAINED: usize = 4 << 20;

/// The packet being read, if one is.
#[derive(Default)]
pub(crate) struct PendingBlock {
    /// Whether a packet is half read: the one at the start of the input
    /// until it is whole.
    active: bool,
    /// Where the block starts in the packet: after its type and table name.
    body: usize,
    /// With compression: the end in the packet of the frames decompressed
    /// so far, and what they hold.
    raw_end: usize,
    decoded: Vec<u8>,
    frame: Vec<u8>,
    scratch: Vec<u8>,
    walk: BlockWalk,
    /// How many decoded bytes a parse of a block the walk does not know
    /// last ran out at: it is tried again only on more of them.
    tried: Option<usize>,
    /// How many decoded bytes the walk last found too few: it is not walked
    /// again before more come.
    short: Option<usize>,
}

fn would_block() -> Error {
    io::Error::new(io::ErrorKind::WouldBlock, "would block").into()
}

impl PendingBlock {
    /// Reads the packet at the start of `input`, which holds what the last
    /// call had and more: the block and the length of the packet, or
    /// `WouldBlock` while it is not all there.
    pub(crate) fn parse(
        &mut self,
        input: &[u8],
        tz: Tz,
        compress: bool,
        revision: u64,
    ) -> Result<(Block, usize)> {
        if !self.active {
            let mut cursor = Cursor::new(input);
            cursor.read_uvarint()?;
            cursor.skip_string()?;
            let body = cursor.position() as usize;
            *self = PendingBlock {
                active: true,
                body,
                raw_end: body,
                decoded: Vec::new(),
                frame: std::mem::take(&mut self.frame),
                scratch: std::mem::take(&mut self.scratch),
                walk: BlockWalk::default(),
                tried: None,
                short: None,
            };
        }
        let result = if compress {
            self.parse_compressed(input, tz, revision)
        } else {
            self.parse_plain(input, tz, revision)
        };
        match result {
            Err(e) if e.is_would_block() => Err(e),
            done => {
                self.active = false;
                self.decoded = Vec::new();
                // The frame buffers serve the next blocks, unless one large
                // frame would keep them large on an idle connection.
                if self.frame.capacity() > RETAINED {
                    self.frame = Vec::new();
                }
                if self.scratch.capacity() > RETAINED {
                    self.scratch = Vec::new();
                }
                done
            }
        }
    }

    fn parse_plain(&mut self, input: &[u8], tz: Tz, revision: u64) -> Result<(Block, usize)> {
        let body = &input[self.body..];
        let measure = self.walk.walk(body, revision);
        if measure == Measure::Incomplete {
            return Err(would_block());
        }
        let (block, len) = load(body, tz, revision)?;
        check(&measure, len);
        Ok((block, self.body + len))
    }

    fn parse_compressed(&mut self, input: &[u8], tz: Tz, revision: u64) -> Result<(Block, usize)> {
        loop {
            let measure = if self.short == Some(self.decoded.len()) {
                Measure::Incomplete
            } else {
                self.walk.walk(&self.decoded, revision)
            };
            if measure == Measure::Incomplete {
                self.short = Some(self.decoded.len());
            }
            let attempt = match measure {
                Measure::Complete(_) => true,
                Measure::Unknown => self.tried != Some(self.decoded.len()),
                Measure::Incomplete => false,
            };
            if attempt {
                match load(&self.decoded, tz, revision) {
                    Ok((block, len)) => {
                        check(&measure, len);
                        return Ok((block, self.raw_end));
                    }
                    // A column the walk does not know may want more.
                    Err(e) if e.is_would_block() && measure == Measure::Unknown => {
                        self.tried = Some(self.decoded.len());
                    }
                    Err(e) => return Err(e),
                }
            }
            if !self.decompress_next(input)? {
                return Err(would_block());
            }
        }
    }

    /// Decompresses the next frame of the block once it is all there; the
    /// block wants more bytes, so the next bytes are a frame of it.
    fn decompress_next(&mut self, input: &[u8]) -> Result<bool> {
        let raw = &input[self.raw_end..];
        let Some(head) = raw.first_chunk::<FRAME_HEAD_SIZE>() else {
            return Ok(false);
        };
        // A header the frame reader rejects is an error now, not a wait.
        if raw.len() < frame_len(head)? {
            return Ok(false);
        }
        let mut cursor = Cursor::new(raw);
        decompress_frame(&mut cursor, &mut self.scratch, &mut self.frame)?;
        self.raw_end += cursor.position() as usize;
        self.decoded.extend_from_slice(&self.frame);
        Ok(true)
    }
}

/// The block at the start of `bytes` and its length.
fn load(bytes: &[u8], tz: Tz, revision: u64) -> Result<(Block, usize)> {
    let mut cursor = Cursor::new(bytes);
    let block = Block::raw_load(&mut cursor, tz, revision)?;
    Ok((block, cursor.position() as usize))
}

/// In the tests, a walk that said whole agrees with the parser.
fn check(measure: &Measure, len: usize) {
    if let Measure::Complete(walked) = measure {
        debug_assert_eq!(*walked, len, "the walk and the parser disagree");
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::{
        binary::Encoder,
        types::{Compression, Simple},
    };

    /// A Data packet of `block` at `revision`, then a Pong.
    fn packet(block: &Block<Simple>, compression: Compression, revision: u64) -> Vec<u8> {
        let mut encoder = Encoder::new();
        encoder.uvarint(1);
        encoder.string("");
        block.write_at(&mut encoder, compression, revision).unwrap();
        encoder.write(4_u8);
        encoder.get_buffer()
    }

    #[test]
    fn test_a_packet_read_byte_by_byte() {
        let strings: Vec<String> = (0..70_000).map(|i| format!("value {i}")).collect();
        let numbers: Vec<u64> = (0..70_000).collect();
        let block = Block::<Simple>::new()
            .column("s", strings)
            .column("n", numbers)
            .column("o", vec![Some(1_u8); 70_000]);
        for compression in [Compression::None, Compression::Lz4, Compression::Zstd] {
            for revision in [54491, 54492] {
                let bytes = packet(&block, compression, revision);
                let end = bytes.len() - 1;
                let mut pending = PendingBlock::default();
                // Every byte short of the whole packet waits: in steps, so
                // that a frame comes whole between some of them.
                let mut len = 0;
                while len < end {
                    let err = pending
                        .parse(&bytes[..len], Tz::UTC, compression.is_enabled(), revision)
                        .expect_err("a packet not all there");
                    assert!(
                        err.is_would_block(),
                        "{compression} {revision} {len}: {err}"
                    );
                    len += 4099;
                }
                let (read, packet_len) = pending
                    .parse(&bytes, Tz::UTC, compression.is_enabled(), revision)
                    .unwrap();
                assert_eq!(read, block, "{compression} {revision}");
                assert_eq!(packet_len, end, "{compression} {revision}");
                assert!(!pending.active);
                // At once, too.
                let (read, _) = PendingBlock::default()
                    .parse(&bytes, Tz::UTC, compression.is_enabled(), revision)
                    .unwrap();
                assert_eq!(read, block);
            }
        }
    }

    #[test]
    fn test_a_bad_frame_header_is_an_error_at_once() {
        // A Data packet whose first frame has a method no reader knows and
        // no payload yet.
        let mut bytes = vec![1, 0];
        bytes.extend_from_slice(&[0; 16]);
        bytes.push(0x77);
        bytes.extend_from_slice(&1000_u32.to_le_bytes());
        bytes.extend_from_slice(&991_u32.to_le_bytes());
        let err = PendingBlock::default()
            .parse(&bytes, Tz::UTC, true, 54492)
            .expect_err("an unknown method");
        assert!(
            err.to_string().contains("unsupported compression method"),
            "{err}"
        );
    }

    #[test]
    fn test_a_replicated_index_past_its_rows_is_an_error_at_once() {
        // A block of one replicated String column of two rows, index 3 of 2
        // distinct rows, and the distinct rows not sent.
        let mut body = Encoder::new();
        body.write_bytes(&[1, 0, 2, 0xff, 0xff, 0xff, 0xff, 0]);
        body.uvarint(1);
        body.uvarint(2);
        body.string("c");
        body.string("String");
        body.write_bytes(&[1, 4]);
        body.uvarint(2);
        body.write_bytes(&[1, 0, 3]);
        body.uvarint(2);
        let body = body.get_buffer();
        for compression in [Compression::None, Compression::Lz4] {
            let mut bytes = vec![1, 0];
            if compression.is_enabled() {
                crate::types::block::compression::compress(compression, 3, &body, &mut bytes)
                    .unwrap();
            } else {
                bytes.extend_from_slice(&body);
            }
            let err = PendingBlock::default()
                .parse(&bytes, Tz::UTC, compression.is_enabled(), 54492)
                .expect_err("an index past the distinct rows");
            assert!(
                err.to_string().contains("points to row 3"),
                "{compression}: {err}"
            );
        }
    }

    #[test]
    fn test_corrupt_frame_is_an_error() {
        let block = Block::<Simple>::new().column("n", vec![1_u32, 2, 3]);
        let mut bytes = packet(&block, Compression::Lz4, 54492);
        // The first byte of the checksum, after the packet type and name.
        bytes[2] ^= 0xff;
        let err = PendingBlock::default()
            .parse(&bytes, Tz::UTC, true, 54492)
            .expect_err("a corrupt frame");
        assert!(!err.is_would_block(), "{err}");
    }
}