/*
 * 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
 */

//! `Time` (an `Int32` of seconds) and `Time64(N)` (an `Int64` of ticks with
//! `N` fraction digits) columns: times of day and durations, negative and
//! past 24 hours as the server allows (`DataTypeTime`, `DataTypeTime64`).
//!
//! Rust values are `chrono::Duration`s; inserted they make a `Time64(9)`
//! column, which goes into `Time` and `Time64(N)` columns when every value
//! converts without losing a digit.

use std::sync::Arc;

use chrono::Duration;
use chrono_tz::Tz;

use crate::{
    binary::{Encoder, ReadEx},
    errors::{Error, Result},
    types::{
        column::{
            column_data::{ArcColumnData, BoxColumnData, ColumnData},
            list::List,
            nullable::NullableColumnData,
            numeric::save_data,
            ColumnFrom, ColumnWrapper,
        },
        SqlType, Value, ValueRef,
    },
};

/// The most fraction digits of a Time64, nanoseconds.
pub(crate) const MAX_PRECISION: u32 = 9;

/// A `Time` (`precision` `None`) or `Time64(precision)` column.
pub(crate) struct TimeColumnData {
    /// Seconds or ticks; a `Time` keeps them as `Int32` on the wire.
    data: TimeData,
    precision: Option<u32>,
}

enum TimeData {
    Seconds(List<i32>),
    Ticks(List<i64>),
}

impl TimeColumnData {
    pub(crate) fn load<R: ReadEx>(
        reader: &mut R,
        precision: Option<u32>,
        size: usize,
    ) -> Result<Self> {
        let data = match precision {
            None => {
                let mut data = List::zeroed(size);
                reader.read_bytes(data.as_mut())?;
                TimeData::Seconds(data)
            }
            Some(_) => {
                let mut data = List::zeroed(size);
                reader.read_bytes(data.as_mut())?;
                TimeData::Ticks(data)
            }
        };
        Ok(TimeColumnData { data, precision })
    }

    pub(crate) fn with_capacity(precision: Option<u32>, capacity: usize) -> Self {
        let data = match precision {
            None => TimeData::Seconds(List::with_capacity(capacity)),
            Some(_) => TimeData::Ticks(List::with_capacity(capacity)),
        };
        TimeColumnData { data, precision }
    }
}

fn pow10(n: u32) -> i64 {
    10_i64.pow(n)
}

/// The ticks of a `Time` or `Time64` `value` at `precision` fraction digits
/// (0 for a `Time`), or `None` when that loses a digit or overflows.
pub(crate) fn time_ticks(value: &Value, precision: u32) -> Option<i64> {
    let (ticks, from) = match value {
        Value::Time(seconds) => (i64::from(*seconds), 0),
        Value::Time64(ticks, precision) => (*ticks, *precision),
        _ => return None,
    };
    if precision > MAX_PRECISION || from > MAX_PRECISION {
        return None;
    }
    if precision >= from {
        ticks.checked_mul(pow10(precision - from))
    } else {
        let factor = pow10(from - precision);
        (ticks % factor == 0).then(|| ticks / factor)
    }
}

/// Whether a time `value` can be stored in a column of `sql_type`: a Time
/// takes whole seconds of `Int32`, a Time64 the ticks of its precision.
/// Values of other types are not this check's concern.
pub(crate) fn time_fits(sql_type: &SqlType, value: &Value) -> bool {
    if !matches!(value, Value::Time(_) | Value::Time64(..)) {
        return true;
    }
    match sql_type {
        SqlType::Time => time_ticks(value, 0).is_some_and(|s| i32::try_from(s).is_ok()),
        SqlType::Time64(precision) => time_ticks(value, *precision).is_some(),
        _ => true,
    }
}

/// The duration of `ticks` at `precision` fraction digits.
pub(crate) fn ticks_to_duration(ticks: i64, precision: u32) -> Option<Duration> {
    if precision > MAX_PRECISION {
        return None;
    }
    // Whole seconds and the fraction apart, so that only a duration chrono
    // cannot hold fails.
    let factor = pow10(precision);
    let nanos = (ticks % factor) * pow10(MAX_PRECISION - precision);
    Duration::try_seconds(ticks / factor)?.checked_add(&Duration::nanoseconds(nanos))
}

/// `[-]h:mm:ss[.fraction]`, hours past 24 included, as ClickHouse prints it.
pub(crate) fn format_time(ticks: i64, precision: u32) -> String {
    if precision > MAX_PRECISION {
        return format!("Time64({ticks} ticks of precision {precision})");
    }
    let factor = pow10(precision) as u64;
    let magnitude = ticks.unsigned_abs();
    let (seconds, fraction) = (magnitude / factor, magnitude % factor);
    let sign = if ticks < 0 { "-" } else { "" };
    let text = format!(
        "{sign}{:02}:{:02}:{:02}",
        seconds / 3600,
        seconds / 60 % 60,
        seconds % 60
    );
    if precision == 0 {
        text
    } else {
        format!("{text}.{fraction:0width$}", width = precision as usize)
    }
}

impl ColumnFrom for Vec<Duration> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        let precision = durations_precision(source.iter().copied());
        let data = source
            .into_iter()
            .map(|d| duration_ticks(d, precision))
            .collect();
        W::wrap(TimeColumnData {
            data: TimeData::Ticks(List::from_vec(data)),
            precision: Some(precision),
        })
    }
}

impl ColumnFrom for Vec<Option<Duration>> {
    fn column_from<W: ColumnWrapper>(source: Self) -> W::Wrapper {
        let nulls = source.iter().map(|v| u8::from(v.is_none())).collect();
        let precision = durations_precision(source.iter().flatten().copied());
        let data = source
            .into_iter()
            .map(|v| v.map_or(0, |d| duration_ticks(d, precision)))
            .collect();
        W::wrap(NullableColumnData {
            nulls,
            inner: Arc::new(TimeColumnData {
                data: TimeData::Ticks(List::from_vec(data)),
                precision: Some(precision),
            }),
        })
    }
}

/// The precision durations are kept at: nanoseconds, or whole seconds for
/// durations past the 292 years nanoseconds reach (far past the ±999 hours a
/// server takes, but not a panic).
pub(crate) fn durations_precision(mut durations: impl Iterator<Item = Duration>) -> u32 {
    if durations.all(|d| d.num_nanoseconds().is_some()) {
        MAX_PRECISION
    } else {
        0
    }
}

/// The ticks of `duration` at `precision` (9 or 0, see [`durations_precision`]).
pub(crate) fn duration_ticks(duration: Duration, precision: u32) -> i64 {
    match (precision, duration.num_nanoseconds()) {
        (MAX_PRECISION, Some(nanos)) => nanos,
        _ => duration.num_seconds(),
    }
}

impl ColumnData for TimeColumnData {
    fn sql_type(&self) -> SqlType {
        match self.precision {
            None => SqlType::Time,
            Some(precision) => SqlType::Time64(precision),
        }
    }

    fn save(&self, encoder: &mut Encoder, start: usize, end: usize) {
        match &self.data {
            TimeData::Seconds(data) => save_data::<i32>(data.as_ref(), encoder, start, end),
            TimeData::Ticks(data) => save_data::<i64>(data.as_ref(), encoder, start, end),
        }
    }

    fn len(&self) -> usize {
        match &self.data {
            TimeData::Seconds(data) => data.len(),
            TimeData::Ticks(data) => data.len(),
        }
    }

    fn push(&mut self, value: Value) {
        // Block::push checks this first and returns an error.
        let ticks = time_ticks(&value, self.precision.unwrap_or(0));
        let sql_type = self.sql_type();
        match (&mut self.data, ticks) {
            (TimeData::Seconds(data), Some(seconds)) if i32::try_from(seconds).is_ok() => {
                data.push(seconds as i32)
            }
            (TimeData::Ticks(data), Some(ticks)) => data.push(ticks),
            _ => panic!("{value} does not fit into {sql_type}"),
        }
    }

    fn at(&self, index: usize) -> ValueRef<'_> {
        match (&self.data, self.precision) {
            (TimeData::Seconds(data), _) => ValueRef::Time(data.at(index)),
            (TimeData::Ticks(data), precision) => {
                ValueRef::Time64(data.at(index), precision.unwrap_or(0))
            }
        }
    }

    fn clone_instance(&self) -> BoxColumnData {
        let data = match &self.data {
            TimeData::Seconds(data) => TimeData::Seconds(data.clone()),
            TimeData::Ticks(data) => TimeData::Ticks(data.clone()),
        };
        Box::new(TimeColumnData {
            data,
            precision: self.precision,
        })
    }

    /// Time and Time64 of any precision cast into each other when every
    /// value converts without losing a digit.
    fn cast_to(&self, _this: &ArcColumnData, target: &SqlType) -> Option<ArcColumnData> {
        cast_times(self, target).ok()
    }

    fn get_timezone(&self) -> Option<Tz> {
        None
    }
}

/// Casts a column of times to the `Time` or `Time64` `target`, or an error
/// naming the first value that does not fit.
pub(crate) fn cast_times(
    column: &(dyn ColumnData + Send + Sync),
    target: &SqlType,
) -> Result<ArcColumnData> {
    let precision = match target {
        SqlType::Time => None,
        SqlType::Time64(precision) if *precision <= MAX_PRECISION => Some(*precision),
        _ => return Err(Error::Other(format!("{target} is not a time type").into())),
    };
    let mut cast = TimeColumnData::with_capacity(precision, column.len());
    for index in 0..column.len() {
        let value = Value::from(column.at(index));
        if !matches!(value, Value::Time(_) | Value::Time64(..)) || !time_fits(target, &value) {
            return Err(Error::Other(
                format!("the value {value} does not fit into {target}").into(),
            ));
        }
        cast.push(value);
    }
    Ok(Arc::new(cast))
}

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

    #[test]
    fn test_ticks_and_text() {
        assert_eq!(time_ticks(&Value::Time(5), 3), Some(5_000));
        assert_eq!(time_ticks(&Value::Time64(1_500, 3), 0), None);
        assert_eq!(time_ticks(&Value::Time64(2_000, 3), 0), Some(2));
        assert_eq!(time_ticks(&Value::Time64(-1, 9), 6), None);
        assert_eq!(time_ticks(&Value::Time64(i64::MAX, 0), 9), None);
        assert!(!time_fits(
            &SqlType::Time,
            &Value::Time64(i64::from(i32::MAX) + 1, 0)
        ));
        assert_eq!(format_time(-45_296, 0), "-12:34:56");
        assert_eq!(format_time(360_000_123_456, 6), "100:00:00.123456");
        assert_eq!(format_time(5, 3), "00:00:00.005");
        assert_eq!(
            ticks_to_duration(-1_500, 3),
            Some(Duration::milliseconds(-1_500))
        );
        // Seconds that nanoseconds cannot hold are still a duration.
        assert_eq!(
            ticks_to_duration(10_000_000_000, 0),
            Some(Duration::seconds(10_000_000_000))
        );
        assert_eq!(
            format_time(1, 1_000_000),
            "Time64(1 ticks of precision 1000000)"
        );
        let long = Duration::days(110_000);
        assert_eq!(Value::from(long), Value::Time64(long.num_seconds(), 0));
    }
}