use std::time::{SystemTime, UNIX_EPOCH};

use log::trace;

use crate::{
    binary::{protocol, Encoder},
    client_info,
    errors::{Error, Result},
    types::{query_param, Context, Options, Query, SettingType, Simple},
    Block,
};

/// Represents Clickhouse commands.
pub(crate) enum Cmd {
    Hello(Context),
    /// Sent after the server's Hello at this negotiated revision, not answered.
    Addendum(u64),
    Ping,
    SendQuery(Query, Context),
    SendData(Block, Context),
    Union(Box<Cmd>, Box<Cmd>),
    Cancel,
}

impl Cmd {
    /// Returns the packed command as a byte vector.
    #[inline(always)]
    pub(crate) fn get_packed_command(&self) -> Result<Vec<u8>> {
        encode_command(self)
    }
}

/// `BaseSettingsHelpers::Flags::CUSTOM`: a value that is not a setting.
const SETTING_FLAG_CUSTOM: u64 = 0x02;

#[derive(Debug, PartialOrd, PartialEq)]
enum SettingsBinaryFormat {
    Old,
    Strings,
}

fn encode_command(cmd: &Cmd) -> Result<Vec<u8>> {
    match cmd {
        Cmd::Hello(context) => encode_hello(context),
        Cmd::Addendum(revision) => Ok(encode_addendum(*revision)),
        Cmd::Ping => Ok(encode_ping()),
        Cmd::SendQuery(query, context) => encode_query(query, context),
        Cmd::SendData(block, context) => encode_data(block, context),
        Cmd::Union(first, second) => encode_union(first.as_ref(), second.as_ref()),
        Cmd::Cancel => Ok(encode_cancel()),
    }
}

fn encode_hello(context: &Context) -> Result<Vec<u8>> {
    trace!("[hello]        -> {}", client_info::description());

    let mut encoder = Encoder::new();
    encoder.uvarint(protocol::CLIENT_HELLO);
    client_info::write(&mut encoder);

    let options = context.options.get()?;

    encoder.string(&options.database);
    encoder.string(&options.username);
    encoder.string(&options.password);

    Ok(encoder.get_buffer())
}

fn encode_ping() -> Vec<u8> {
    trace!("[ping]         -> ping");

    let mut encoder = Encoder::new();
    encoder.uvarint(protocol::CLIENT_PING);
    encoder.get_buffer()
}

fn encode_cancel() -> Vec<u8> {
    trace!("[cancel]");

    let mut encoder = Encoder::new();
    encoder.uvarint(protocol::CLIENT_CANCEL);
    encoder.get_buffer()
}

fn encode_query(query: &Query, context: &Context) -> Result<Vec<u8>> {
    trace!("[send query] {}", query.get_sql());

    // The fields of ClientInfo::write and Connection::sendQuery, by revision.
    let revision = client_info::negotiated(context.server_info.revision);
    let mut encoder = Encoder::new();
    encoder.uvarint(protocol::CLIENT_QUERY);
    encoder.string("");

    {
        let hostname = &context.hostname;
        encoder.uvarint(1); // query kind: initial
        encoder.string(""); // initial user
        encoder.string(query.get_id()); // initial query id
        encoder.string("[::ffff:127.0.0.1]:0"); // initial address
        if revision >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_INITIAL_QUERY_START_TIME {
            encoder.write(start_time_microseconds());
        }
        encoder.uvarint(1); // interface: TCP
        encoder.string(hostname); // OS user
        encoder.string(hostname); // client host name
    }
    client_info::write(&mut encoder);

    if revision >= protocol::DBMS_MIN_REVISION_WITH_QUOTA_KEY_IN_CLIENT_INFO {
        encoder.string("");
    }

    if revision >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_DISTRIBUTED_DEPTH {
        encoder.uvarint(0);
    }

    if revision >= protocol::DBMS_MIN_REVISION_WITH_VERSION_PATCH {
        encoder.uvarint(0);
    }

    if revision >= protocol::DBMS_MIN_REVISION_WITH_OPENTELEMETRY {
        encoder.write(0_u8); // no trace context
    }

    if revision >= protocol::DBMS_MIN_REVISION_WITH_PARALLEL_REPLICAS {
        encoder.uvarint(0); // collaborate with the initiator
        encoder.uvarint(0); // count of participating replicas
        encoder.uvarint(0); // number of the current replica
    }

    if revision >= protocol::DBMS_MIN_REVISION_WITH_QUERY_AND_LINE_NUMBERS {
        encoder.uvarint(0); // number of the query in a script
        encoder.uvarint(0); // its line
    }

    if revision >= protocol::DBMS_MIN_REVISON_WITH_JWT_IN_INTERSERVER {
        encoder.write(0_u8); // no JWT
    }

    if revision >= protocol::DBMS_MIN_REVISION_WITH_CLIENT_AGENT_IN_CLIENT_INFO {
        encoder.string(""); // no client agent
    }

    if revision >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_INTERNAL_QUERY_FLAG {
        encoder.write(0_u8); // not a query the server runs for itself
    }

    if revision >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_INTERSERVER_CURRENT_ROLES {
        encoder.write(0_u8); // no current roles
    }

    let options = context.options.get()?;

    let settings_format =
        if revision >= protocol::DBMS_MIN_REVISION_WITH_SETTINGS_SERIALIZED_AS_STRINGS {
            SettingsBinaryFormat::Strings
        } else {
            SettingsBinaryFormat::Old
        };

    serialize_settings(&mut encoder, &options, settings_format);

    if revision >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_INTERSERVER_EXTERNALLY_GRANTED_ROLES {
        encoder.string(""); // no roles granted by another server
    }

    if revision >= protocol::DBMS_MIN_REVISION_WITH_INTERSERVER_SECRET {
        encoder.string(""); // no cluster secret: not a query between servers
    }

    encoder.uvarint(protocol::STATE_COMPLETE);

    encoder.uvarint(if options.compression.is_enabled() {
        protocol::COMPRESS_ENABLE
    } else {
        protocol::COMPRESS_DISABLE
    });

    encoder.string(query.get_sql());

    let params = query.get_params();
    if revision >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_PARAMETERS {
        // As writeQueryParameters: name, the CUSTOM flag, the quoted text.
        for (name, value) in params {
            // An empty name ends the list.
            if name.is_empty() {
                return Err(Error::Other("a query parameter needs a name".into()));
            }
            encoder.string(name);
            encoder.uvarint(SETTING_FLAG_CUSTOM);
            encoder.byte_string(query_param::quote(&query_param::param_text(value)));
        }
        encoder.string(""); // end of the query parameters
    } else if !params.is_empty() {
        return Err(Error::Other(
            format!(
                "query parameters need protocol revision {}; the server speaks {revision}",
                protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_PARAMETERS
            )
            .into(),
        ));
    }

    Block::<Simple>::default().send_data(
        &mut encoder,
        options.compression,
        options.zstd_level(),
        revision,
    )?;

    Ok(encoder.get_buffer())
}

/// The start of an initial query in microseconds since the epoch, as
/// clickhouse-client sends it.
fn start_time_microseconds() -> i64 {
    SystemTime::now()
        .duration_since(UNIX_EPOCH)
        .map_or(0, |since| since.as_micros() as i64)
}

/// The addendum a client sends right after the server's Hello: the quota key
/// and, from 54470, the framing it sends and takes: never chunked.
fn encode_addendum(revision: u64) -> Vec<u8> {
    trace!("[addendum]     -> quota key");

    let mut encoder = Encoder::new();
    encoder.string("");
    if revision >= protocol::DBMS_MIN_PROTOCOL_VERSION_WITH_CHUNKED_PACKETS {
        encoder.string("notchunked");
        encoder.string("notchunked");
    }
    // This client takes no part in the parallel replicas protocol.
    if revision >= protocol::DBMS_MIN_REVISION_WITH_VERSIONED_PARALLEL_REPLICAS_PROTOCOL {
        encoder.uvarint(0);
    }
    encoder.get_buffer()
}

fn serialize_settings(encoder: &mut Encoder, options: &Options, format: SettingsBinaryFormat) {
    if format < SettingsBinaryFormat::Strings {
        for (name, value) in &options.settings {
            encoder.string(name);
            match &value.value {
                SettingType::String(val) => encoder.string(val),
                // Bool and UInt64 is the same
                SettingType::Bool(val) => encoder.uvarint((val == &true) as u64),
                // Float is written in string representation
                SettingType::Float64(val) => encoder.string(val.to_string()),
                SettingType::UInt64(val) => encoder.uvarint(*val),
            }
        }
    } else {
        for (name, value) in &options.settings {
            encoder.string(name);
            encoder.write(value.is_important);
            encoder.string(value.to_string());
        }
    }

    encoder.string(""); // end of settings marker
}

fn encode_data(block: &Block, context: &Context) -> Result<Vec<u8>> {
    let mut encoder = Encoder::new();
    let options = context.options.get()?;
    let revision = client_info::negotiated(context.server_info.revision);
    block.send_data(
        &mut encoder,
        options.compression,
        options.zstd_level(),
        revision,
    )?;
    Ok(encoder.get_buffer())
}

fn encode_union(first: &Cmd, second: &Cmd) -> Result<Vec<u8>> {
    let mut result = encode_command(first)?;
    result.extend((encode_command(second)?).iter());
    Ok(result)
}

#[cfg(test)]
mod test {
    use super::*;
    use crate::types::{Compression, IntoOptions, ServerInfo};

    #[test]
    fn test_params_need_a_server_that_takes_them() {
        let query = Query::new("SELECT {x:UInt8}").param("x", 1_u8);
        let mut context = Context::default();
        context.server_info.revision = 54429;
        let err = encode_query(&query, &context).unwrap_err();
        assert!(err.to_string().contains("revision 54459"), "{err}");
        context.server_info.revision = 54459;
        assert!(encode_query(&query, &context).is_ok());
        // Without parameters, an older server is fine.
        context.server_info.revision = 54429;
        assert!(encode_query(&Query::new("SELECT 1"), &context).is_ok());

        // An empty name would end the list early.
        context.server_info.revision = 54459;
        let nameless = Query::new("SELECT 1").param("", 1_u8);
        assert!(encode_query(&nameless, &context).is_err());
        // Debug shows the names, not the values.
        let secret = Query::new("SELECT {p:String}").param("p", "hunter2");
        let debug = format!("{secret:?}");
        assert!(
            debug.contains("\"p\"") && !debug.contains("hunter2"),
            "{debug}"
        );
    }

    #[test]
    fn test_send_data_uses_the_connection_zstd_level() {
        let numbers: Vec<u64> = (0..100_000_u64).map(|i| i * i % 1000).collect();
        let block = Block::new().column("n", numbers);
        let mut raw = Encoder::new();
        block.write(&mut raw, Compression::None).unwrap();
        let raw = raw.get_buffer();
        let reference = |level| zstd::bulk::compress(&raw, level).unwrap();
        assert_ne!(
            reference(1),
            reference(9),
            "the block must tell the levels apart"
        );

        for level in [1, 9] {
            let options = Options::default()
                .compression(Compression::Zstd)
                .with_setting("network_zstd_compression_level", level as u64, true);
            // A server of this client's revision, as the reference block is.
            let context = Context {
                options: options.into_options_src(),
                server_info: ServerInfo {
                    revision: client_info::CLICK_HOUSE_REVISION,
                    ..ServerInfo::default()
                },
                ..Context::default()
            };
            let packet = encode_data(&block, &context).unwrap();
            // CLIENT_DATA and the empty table name take a byte each; the block
            // fits one frame: 16 bytes of checksum, a 9-byte header, the payload.
            let payload = &packet[2 + 16 + 9..];
            assert_eq!(payload, &reference(level)[..], "level {level}");
        }
    }
}