use std::{
    cell::Cell,
    fmt::Debug,
    marker::PhantomData,
    str::FromStr,
    sync::atomic::{AtomicU8, Ordering},
    time::{Duration, SystemTime},
};

#[cfg(feature = "bytemuck")]
use bytemuck::{Pod, TransparentWrapper, Zeroable};
use rand::{Rng, rng};
use rapira::{Rapira, RapiraError};
use rend::u64_be;
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout};

use super::{ArmourError, IdStr, Result, enc::IdHasher, num_ops::g8bits};
use crate::{
    Cid, GetType, KeyScheme, KeyType, Typ, cid::MILLISECOND_BITS, types::key_part::KeyPart,
};

/// different from the unix timestamp epoch in milliseconds
///
/// 2023-04-09 0:00:00 UTC
const TS_DIFF: u64 = 0x187_6350_0000;

const TS_BITS: u32 = 40;
const TS_MAX: u64 = (1 << TS_BITS) - 1;
// 64 - 40 = 24
const TS_SHIFT: u32 = u64::BITS - TS_BITS;

// 2^8 = 256
pub(crate) const SHARD_BITS: u32 = 8;
// 255
pub const SHARD_ID_MAX: u64 = (1 << SHARD_BITS) - 1;

/// 16 bits
const SEQ_BITS: u32 = u64::BITS - TS_BITS - SHARD_BITS;
/// 65_535 max sequence
const SEQ_MAX: u64 = (1 << SEQ_BITS) - 1;

// 2^3 = 8
const SHARD_INST_BITS: u32 = 3;
// 7
pub const SHARD_INSTANCE_ID_MAX: u64 = (1 << SHARD_INST_BITS) - 1;
// 5 + 16 = 21
const SHARD_INSTANCE_SHIFT: u32 = SHARD_THREAD_BITS + SEQ_BITS;

// 2^5 = 32
pub const SHARD_THREAD_BITS: u32 = 5;
// 31
pub const SHARD_THREAD_ID_MAX: u64 = (1 << SHARD_THREAD_BITS) - 1;

#[derive(Debug, Clone, Copy)]
struct SeqForMs {
    /// timestamp in milliseconds
    ts: u64,
    seq: u64,
    count: u64,
}

impl SeqForMs {
    #[cfg(feature = "std")]
    #[inline]
    fn with_ts_and_rand_seq(ts: u64) -> Self {
        let seq = rng().random_range(0..=SEQ_MAX);

        SeqForMs { ts, seq, count: 0 }
    }

    #[cold]
    fn wait_inc(self, ts: u64, duration: Duration) -> Self {
        info!(?duration, "wait_inc");
        let nanos = duration.subsec_nanos() % 1_000_000;
        let wait_nanos = 1_000_000 - nanos;
        std::thread::sleep(Duration::from_nanos(wait_nanos as u64));

        SeqForMs::with_ts_and_rand_seq(ts + 1)
    }

    #[inline]
    fn increment(mut self, ts: u64, duration: Duration) -> Self {
        if self.count == SEQ_MAX {
            self.wait_inc(ts, duration)
        } else {
            if self.seq == SEQ_MAX {
                self.seq = 0;
            } else {
                self.seq += 1;
            }
            self.count += 1;
            self
        }
    }
}

static THREAD_SEQ: AtomicU8 = AtomicU8::new(0);

thread_local! {
    static SEQ_CHECK: Cell<SeqForMs> = Cell::new(SeqForMs::with_ts_and_rand_seq(0));
    static THREAD_ID: Cell<u8> = Cell::new(THREAD_SEQ.fetch_add(1, Ordering::Relaxed));
}

/// - 64bit id [--timestamp(40)--|--shard_id(8)--|--seq_id(16)--]
/// - 40 bit - timestamp (in milliseconds) started from 2023-04-09 0:00:00 UTC, 34 years available (from 2023 to 2057)
/// - 8 bit - shard_id ([datacenter_id / instance_id] with thread_id), 256 values
/// - 16 bit - random sequence id (unique for thread / per thread), 65_536 values
/// - Blowfish for encryption
/// - ZBASE32 for encoding into 13 length string
/// - create ~ 50ns (~ 21k in 1ms or 21m in 1s) in 1 thread
///
/// Notes:
/// - checks timestamp and shard_id when deserialized from string
/// - Fuid is not inlined for InlineArray
#[derive(Hash, IntoBytes, FromBytes, Immutable, KnownLayout)]
#[cfg_attr(
    feature = "rkyv",
    derive(rkyv::Archive, rkyv::Serialize, rkyv::Deserialize)
)]
#[cfg_attr(feature = "bytemuck", derive(TransparentWrapper))]
#[cfg_attr(feature = "bytemuck", transparent(u64_be))]
#[cfg_attr(feature = "bitcode", derive(bitcode::Encode, bitcode::Decode))]
#[repr(transparent)]
pub struct Fuid<H>(pub u64_be, PhantomData<H>);

#[cfg(feature = "bytemuck")]
unsafe impl<T> Zeroable for Fuid<T> {}
#[cfg(feature = "bytemuck")]
unsafe impl<T: 'static> Pod for Fuid<T> {}

impl<T> Clone for Fuid<T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Fuid<T> {}

impl<H> Fuid<H> {
    pub fn from_thread() -> Self {
        let thread_id = THREAD_ID.get();
        Self::with_shard(thread_id as u64)
    }

    /// - 3 bit - instance id (datacenter id / shard id) (max 7)
    /// - 5 bit - thread id (max 31)
    /// - instance_id (datacenter) < 8 and thread_id (worker) < 32
    #[cfg(feature = "std")]
    #[inline]
    pub fn with_inst_thread(instance_id: u64, thread_id: u64) -> Self {
        assert!(instance_id <= SHARD_INSTANCE_ID_MAX);
        assert!(thread_id <= SHARD_THREAD_ID_MAX);

        let shard_id = (instance_id << SHARD_THREAD_BITS) | thread_id;
        Self::with_shard(shard_id)
    }

    /// Create a new Fuid.
    /// - shard_id < 256
    #[cfg(feature = "std")]
    pub fn with_shard(shard_id: u64) -> Self {
        assert!(shard_id <= SHARD_ID_MAX);

        let now = SystemTime::now();
        // in ms
        #[allow(clippy::unwrap_used)]
        let duration = now.duration_since(SystemTime::UNIX_EPOCH).unwrap();
        let timestamp = duration.as_millis() as u64;

        let new_epoch_ts = timestamp - TS_DIFF;

        let id = new_epoch_ts << TS_SHIFT;

        let id = id | (shard_id << SEQ_BITS);

        let mut seq_check = SEQ_CHECK.get();

        if seq_check.ts == timestamp {
            seq_check = seq_check.increment(timestamp, duration);
        } else {
            seq_check = SeqForMs::with_ts_and_rand_seq(timestamp);
        }
        SEQ_CHECK.set(seq_check);

        let id = id | seq_check.seq;

        Self(u64_be::from_native(id), PhantomData)
    }

    /// unix timestamp in milliseconds
    #[inline]
    pub fn timestamp(&self) -> u64 {
        let ts = self.0.to_native() >> TS_SHIFT;
        ts + TS_DIFF
    }

    pub fn date(&self) -> time::OffsetDateTime {
        let ts = self.timestamp();
        let ts = ts as i128;
        let ts = ts * 1_000_000;
        let dt = time::OffsetDateTime::from_unix_timestamp_nanos(ts);
        dt.expect("invalid timestamp")
    }

    /// get LE u64
    #[inline]
    pub fn get(&self) -> u64 {
        self.0.to_native()
    }

    #[inline]
    pub fn to_be_bytes(self) -> [u8; 8] {
        zerocopy::transmute!(self)
    }

    #[inline]
    pub fn from_be_bytes(bytes: [u8; 8]) -> Self {
        zerocopy::transmute!(bytes)
    }

    /// to BE bytes
    #[inline]
    pub fn to_bytes(self) -> [u8; 8] {
        zerocopy::transmute!(self)
    }

    /// from BE bytes
    #[inline]
    pub fn from_bytes(bytes: [u8; 8]) -> Self {
        zerocopy::transmute!(bytes)
    }

    /// to BE u64
    #[inline]
    pub fn to_u64(self) -> u64 {
        zerocopy::transmute!(self)
    }

    /// from BE u64
    #[inline]
    pub fn from_u64(bytes: u64) -> Self {
        zerocopy::transmute!(bytes)
    }

    #[inline]
    pub fn to_le_bytes(self) -> [u8; 8] {
        self.0.to_native().to_le_bytes()
    }

    #[inline]
    pub fn instance_id(&self) -> u64 {
        let ts = self.0.to_native() >> SHARD_INSTANCE_SHIFT;
        ts & SHARD_INSTANCE_ID_MAX
    }

    #[inline]
    pub fn thread_id(&self) -> u64 {
        let ts = self.0.to_native() >> SEQ_BITS;
        ts & SHARD_THREAD_ID_MAX
    }

    #[inline]
    pub fn shard_id(&self) -> u64 {
        let ts = self.0.to_native() >> SEQ_BITS;
        ts & SHARD_ID_MAX
    }

    #[inline]
    fn seq(&self) -> u64 {
        let ts = self.0.to_native();
        ts & SEQ_MAX
    }

    /// id: {id:#x}; {id:#b}; {dt}-{instance_id}-{thread_id}-{seq}
    #[cfg(feature = "std")]
    pub fn format<W>(&self, w: &mut W) -> Result<(), core::fmt::Error>
    where
        W: std::fmt::Write,
    {
        let id = self.0.to_native();
        let dt = self.date();
        let instance_id = self.instance_id();
        let thread_id = self.thread_id();
        let seq = self.seq();
        write!(
            w,
            "id: {id:#x}; {id:#b}; {dt}-{instance_id}-{thread_id}-{seq}"
        )
    }

    /// return prefix for date [--timestamp(5)--|0x00(1)|0x0000(2)]
    /// ms - unix timestamp in milliseconds
    pub fn date_prefix(ms: u64) -> [u8; 8] {
        let ts = (ms - TS_DIFF) << TS_SHIFT;
        ts.to_be_bytes()
    }

    pub fn check(&self) -> Result<(), ArmourError> {
        let ts = self.0.to_native() >> TS_SHIFT;
        if ts > TS_MAX {
            return Err(ArmourError::IdDecodeError);
        }
        Ok(())
    }

    /// only for iterator with excluded bounds
    pub fn increment(mut self) -> Self {
        self.0 += 1;
        self
    }
}

impl<H: IdHasher> Fuid<H> {
    pub fn ser(self) -> IdStr {
        let u: u64 = zerocopy::transmute!(self);
        H::ser(u)
    }

    pub fn deser(id: &str) -> Result<Self, ArmourError> {
        let id = H::deser(id)?;
        Ok(zerocopy::transmute!(id))
    }
}

impl Fuid<()> {
    pub fn ser(self) -> IdStr {
        let u: [u8; 8] = zerocopy::transmute!(self);
        super::enc::encode(&u)
    }

    pub fn deser(id: &str) -> Result<Self, ArmourError> {
        let id = super::enc::decode(id)?;
        Ok(zerocopy::transmute!(id))
    }
}

impl<T> PartialOrd for Fuid<T> {
    fn partial_cmp(&self, other: &Self) -> Option<core::cmp::Ordering> {
        Some(self.cmp(other))
    }
}

impl<T> Ord for Fuid<T> {
    fn cmp(&self, other: &Self) -> core::cmp::Ordering {
        self.0.cmp(&other.0)
    }
}

impl<T> PartialEq for Fuid<T> {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}

impl<T> Eq for Fuid<T> {}

impl<T> PartialEq<[u8; 8]> for Fuid<T> {
    fn eq(&self, other: &[u8; 8]) -> bool {
        let bytes: &[u8; 8] = zerocopy::transmute_ref!(self);
        bytes == other
    }
}

impl<T> PartialEq<Fuid<T>> for [u8; 8] {
    fn eq(&self, other: &Fuid<T>) -> bool {
        let bytes: &[u8; 8] = zerocopy::transmute_ref!(other);
        bytes == self
    }
}

impl<T> PartialEq<Fuid<T>> for Option<Fuid<T>> {
    fn eq(&self, other: &Fuid<T>) -> bool {
        match self {
            Some(id) => id == other,
            None => false,
        }
    }
}

impl<T> PartialEq<Option<Fuid<T>>> for Fuid<T> {
    fn eq(&self, other: &Option<Fuid<T>>) -> bool {
        match other {
            Some(id) => self == id,
            None => false,
        }
    }
}

impl<T> AsRef<Self> for Fuid<T> {
    fn as_ref(&self) -> &Self {
        self
    }
}

impl<T> AsRef<[u8; 8]> for Fuid<T> {
    fn as_ref(&self) -> &[u8; 8] {
        zerocopy::transmute_ref!(self)
    }
}

/// only check if non-zero, not check valid byte mask
impl<H> Rapira for Fuid<H> {
    const STATIC_SIZE: Option<usize> = Some(8);
    const MIN_SIZE: usize = 8;

    #[inline]
    fn size(&self) -> usize {
        8
    }

    #[inline]
    fn check_bytes(slice: &mut &[u8]) -> rapira::Result<()> {
        let bytes: &[u8] = slice.get(..8).ok_or(RapiraError::SliceLen)?;

        const ZERO_BYTES: [u8; 8] = [0u8; 8];

        if bytes == ZERO_BYTES {
            return Err(RapiraError::NonZero);
        }

        *slice = unsafe { slice.get_unchecked(8..) };
        Ok(())
    }

    #[inline]
    fn from_slice(slice: &mut &[u8]) -> rapira::Result<Self>
    where
        Self: Sized,
    {
        let bytes = <[u8; 8]>::from_slice(slice)?;
        let id = Self::from_bytes(bytes);
        Ok(id)
    }

    #[inline]
    fn convert_to_bytes(&self, slice: &mut [u8], cursor: &mut usize) {
        let bytes: &[u8; 8] = zerocopy::transmute_ref!(self);
        bytes.convert_to_bytes(slice, cursor);
    }
}

impl<H> GetType for Fuid<H> {
    const TYPE: Typ = Typ::Fuid;
}

impl<H> KeyPart for Fuid<H> {
    const TY: KeyType = KeyType::Fuid;
    const PREFIX_BITS: u32 = MILLISECOND_BITS;
}

impl<H> Cid for Fuid<H> {
    type B = [u8; 8];
    const TY: KeyScheme = KeyScheme::Typed(&[KeyType::Fuid]);
    const GROUP_BITS: u32 = MILLISECOND_BITS;

    #[inline]
    fn encode(&self) -> Self::B {
        zerocopy::transmute!(*self)
    }

    #[inline]
    fn encode_owned(self) -> Self::B {
        zerocopy::transmute!(self)
    }

    #[inline]
    fn decode(bytes: &Self::B) -> Result<Self> {
        Ok(zerocopy::transmute!(*bytes))
    }

    #[inline]
    fn decode_owned(bytes: Self::B) -> Result<Self> {
        Ok(zerocopy::transmute!(bytes))
    }

    /// 12 days one group
    #[inline]
    fn group_id(&self) -> u32 {
        g8bits(self.0.to_native(), Self::GROUP_BITS)
    }
}

impl<H: IdHasher> std::fmt::Display for Fuid<H> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.ser())
    }
}

impl std::fmt::Display for Fuid<()> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{}", self.ser())
    }
}

impl<H> Debug for Fuid<H> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let id = self.0.to_native();
        let id = format!("{id:#X}");
        f.debug_tuple("Fuid").field(&id).finish()
    }
}

impl<T: IdHasher> TryFrom<&str> for Fuid<T> {
    type Error = ArmourError;
    fn try_from(val: &str) -> Result<Self, Self::Error> {
        Self::deser(val)
    }
}

impl TryFrom<&str> for Fuid<()> {
    type Error = ArmourError;
    fn try_from(val: &str) -> Result<Self, Self::Error> {
        Self::deser(val)
    }
}

impl<T: IdHasher> FromStr for Fuid<T> {
    type Err = ArmourError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::deser(s)
    }
}

impl FromStr for Fuid<()> {
    type Err = ArmourError;
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::deser(s)
    }
}

#[cfg(feature = "std")]
impl<T: IdHasher> Serialize for Fuid<T> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let s = self.ser();
        serializer.serialize_str(&s)
    }
}

#[cfg(feature = "std")]
impl<'de, T: IdHasher> Deserialize<'de> for Fuid<T> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;

        let s: &str = Deserialize::deserialize(deserializer)?;
        let a = Fuid::<T>::deser(s).map_err(|err| {
            error!("id value error: {err}");
            D::Error::custom("id value error")
        })?;
        Ok(a)
    }
}

#[cfg(feature = "std")]
impl Serialize for Fuid<()> {
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let s = self.ser();
        serializer.serialize_str(&s)
    }
}

#[cfg(feature = "std")]
impl<'de> Deserialize<'de> for Fuid<()> {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        use serde::de::Error;

        let s: &str = Deserialize::deserialize(deserializer)?;
        let a = Fuid::<()>::deser(s).map_err(|err| {
            error!("id value error: {err}");
            D::Error::custom("id value error")
        })?;
        Ok(a)
    }
}

#[cfg(feature = "ts-rs")]
impl<H> ts_rs::TS for Fuid<H> {
    type WithoutGenerics = Fuid<()>;
    type OptionInnerType = Self;
    fn name() -> String {
        "Fuid".to_owned()
    }
    fn decl_concrete() -> String {
        format!("type Fuid = {};", Self::inline())
    }
    fn decl() -> String {
        let inline = <Fuid<()> as ::ts_rs::TS>::inline();
        format!("type Fuid = {inline};")
    }
    fn inline() -> String {
        "string".to_owned()
    }
    fn inline_flattened() -> String {
        panic!("{} cannot be flattened", Self::name())
    }
    fn output_path() -> Option<std::path::PathBuf> {
        Some(std::path::PathBuf::from("fuid.ts"))
    }
}

#[cfg(feature = "fake")]
impl<H, T> fake::Dummy<T> for Fuid<H> {
    fn dummy_with_rng<R: Rng + ?Sized>(_: &T, _: &mut R) -> Self {
        Fuid::from_thread()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::types::enc::Cipher;

    #[derive(Debug, PartialOrd, Ord, PartialEq, Eq, Clone, Copy, Hash)]
    pub struct Hasher;

    impl IdHasher for Hasher {
        const HASHER: Cipher = Cipher::new(
            "_mKbKGF2IrkGvIJvl97HuCgWjgt6QRZ7Ye8DHBQ2anvyi18BdMz8uN6Ej3YJApooY6qDu0obqq4",
        );
    }

    #[test]
    fn test_fuid_creation() {
        let fuid = Fuid::<Hasher>::with_inst_thread(1, 2);
        assert_eq!(fuid.instance_id(), 1);
        assert_eq!(fuid.thread_id(), 2);

        let fuid = Fuid::<Hasher>::with_shard(55);
        assert_eq!(fuid.shard_id(), 55);
    }

    #[test]
    fn test_fuid_ser_deser() {
        let fuid = Fuid::<Hasher>::with_shard(111);
        let id_str = fuid.ser();
        #[allow(clippy::unwrap_used)]
        let deserialized_fuid = Fuid::<Hasher>::deser(&id_str).unwrap();
        assert_eq!(fuid, deserialized_fuid);
    }

    #[test]
    fn test_fuid_encode_decode() {
        let fuid = Fuid::<Hasher>::with_shard(255);
        let encoded = fuid.encode();
        #[allow(clippy::unwrap_used)]
        let decoded_fuid = Fuid::<Hasher>::decode(&encoded).unwrap();
        assert_eq!(fuid, decoded_fuid);
    }
}
