use std::{borrow::Borrow, fmt::Debug, ops::RangeBounds};

use fjall::Slice;

use super::{ItemWithRaw, KeyValue, RawTree};
use crate::{Cid, DbError, DbResult, Entry, Record};

#[derive(derive_more::Debug)]
pub struct ReadTree<Item: Record> {
    pub(crate) raw: RawTree,
    pub(crate) phantom: std::marker::PhantomData<Item>,
}

impl<Item: Record> Clone for ReadTree<Item> {
    fn clone(&self) -> Self {
        Self {
            raw: self.raw.clone(),
            phantom: std::marker::PhantomData,
        }
    }
}

impl<Item> ReadTree<Item>
where
    Item: Record<Value = Slice> + Debug,
{
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME), ret)]
    fn get_by_slice(&self, key: &[u8]) -> DbResult<Option<Item>> {
        let start = std::time::Instant::now();
        let val = self.raw.tree.get(key)?;
        let res = match val {
            Some(val) => Ok(Some(Item::deser_owned(val))),
            None => Ok(None),
        };

        histogram!("armour_logdb_tree_get_by_slice_duration", "name" => self.raw.name.clone())
            .record(start.elapsed().as_secs_f64());
        counter!("armour_logdb_tree_get_by_slice_total", "name" => self.raw.name.clone())
            .increment(1);

        res
    }

    /// get value by id
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME), ret)]
    pub fn get(&self, id: impl Borrow<Item::SelfId> + Debug) -> DbResult<Option<Item>> {
        let key = Cid::encode(id.borrow());
        self.get_by_slice(key.as_ref())
    }

    /// get value by id or return not found
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME), ret)]
    pub fn get_or_err(&self, id: impl Borrow<Item::SelfId> + Debug) -> DbResult<Item> {
        let key = Cid::encode(id.borrow());
        self.get_by_slice(key.as_ref())
            .and_then(|item| item.ok_or(DbError::NotFound))
    }

    /// check exist by id
    #[doc(alias = "exists")]
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME), ret)]
    pub fn contains(&self, id: impl Borrow<Item::SelfId> + Debug) -> DbResult<bool> {
        let start = std::time::Instant::now();
        let key = Cid::encode(id.borrow());
        let res = self
            .raw
            .tree
            .contains_key(key.as_ref())
            .map_err(DbError::from);

        histogram!("armour_logdb_tree_contains_duration", "name" => self.raw.name.clone())
            .record(start.elapsed().as_secs_f64());
        counter!("armour_logdb_tree_contains_total", "name" => self.raw.name.clone()).increment(1);

        res
    }

    /// get iterator for collection
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME))]
    pub fn iter(&self) -> impl DoubleEndedIterator<Item = Entry<Item>> {
        counter!("armour_logdb_tree_iter_total", "name" => self.raw.name.clone()).increment(1);
        self.raw
            .tree
            .iter()
            .filter_map(|item| entry_filter_map(item.into_inner()))
    }

    /// get iterator by prefix for collection
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME))]
    pub fn scan_prefix<'a, P>(&'a self, prefix: P) -> impl DoubleEndedIterator<Item = Entry<Item>>
    where
        P: AsRef<[u8]> + Debug + 'a,
    {
        counter!("armour_logdb_tree_scan_prefix_total", "name" => self.raw.name.clone())
            .increment(1);
        self.raw
            .tree
            .prefix(prefix)
            .filter_map(|item| entry_filter_map(item.into_inner()))
    }

    /// get iterator by prefix for collection
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME))]
    pub fn scan_prefix_key<'a, P>(
        &'a self,
        prefix: P,
    ) -> impl DoubleEndedIterator<Item = Item::SelfId> + 'a
    where
        P: AsRef<[u8]> + Debug + 'a,
    {
        counter!("armour_logdb_tree_scan_prefix_key_total", "name" => self.raw.name.clone())
            .increment(1);
        self.raw
            .tree
            .prefix(prefix)
            .filter_map(|entry| match entry.into_inner() {
                Ok((key, _)) => Some(Item::deser_key(&key)),
                Err(e) => {
                    error!(%e);
                    None
                }
            })
    }

    /// get iterator by range for collection
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME))]
    pub fn range_iter<'a, K, R>(&'a self, range: R) -> impl DoubleEndedIterator<Item = Entry<Item>>
    where
        K: AsRef<[u8]> + 'a,
        R: RangeBounds<K> + Debug + 'a,
    {
        counter!("armour_logdb_tree_range_iter_total", "name" => self.raw.name.clone())
            .increment(1);
        self.raw
            .tree
            .range(range)
            .filter_map(|item| entry_filter_map(item.into_inner()))
    }

    /// get iterator by prefix for collection
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME))]
    pub fn try_scan_prefix<'a, P>(
        &'a self,
        prefix: P,
    ) -> impl DoubleEndedIterator<Item = DbResult<Entry<Item>>>
    where
        P: AsRef<[u8]> + Debug + 'a,
    {
        counter!("armour_logdb_tree_try_scan_prefix_total", "name" => self.raw.name.clone())
            .increment(1);
        self.raw
            .tree
            .prefix(prefix)
            .map(|item| entry_map(item.into_inner()))
    }

    /// get iterator by prefix for collection
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME))]
    pub fn try_scan_prefix_with_raw<'a, P>(
        &'a self,
        prefix: P,
    ) -> impl DoubleEndedIterator<Item = DbResult<ItemWithRaw<Item>>>
    where
        P: AsRef<[u8]> + Debug + 'a,
    {
        counter!("armour_logdb_tree_try_scan_prefix_with_raw_total", "name" => self.raw.name.clone()).increment(1);
        self.raw
            .tree
            .prefix(prefix)
            .map(|item| entry_map_with_raw(item.into_inner()))
    }

    /// get iterator by range for collection
    /// if item error, return Error
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME))]
    pub fn try_range_iter<'a, K, R>(
        &'a self,
        range: R,
    ) -> impl DoubleEndedIterator<Item = DbResult<ItemWithRaw<Item>>>
    where
        K: AsRef<[u8]> + 'a,
        R: RangeBounds<K> + Debug + 'a,
    {
        counter!("armour_logdb_tree_try_range_iter_total", "name" => self.raw.name.clone())
            .increment(1);
        self.raw.tree.range(range).map(|item| {
            item.into_inner().map_err(DbError::from).map(|item| {
                let (key, value) = item;
                let id = Item::deser_key(&key);
                let val = Item::deser(&value);
                (key, value, Entry { key: id, val })
            })
        })
    }

    /// iter without deserialize value
    #[instrument(level = "trace", skip(self), fields(name = Item::NAME))]
    pub fn iter_keys(&self) -> impl DoubleEndedIterator<Item = Item::SelfId> {
        counter!("armour_logdb_tree_iter_keys_total", "name" => self.raw.name.clone()).increment(1);
        self.raw.tree.iter().filter_map(|item| match item.key() {
            Ok(key) => Some(Item::deser_key(&key)),
            Err(e) => {
                error!(%e);
                None
            }
        })
    }
}

#[inline]
fn entry_filter_map<Item: Record<Value = Slice>>(
    item: fjall::Result<KeyValue>,
) -> Option<Entry<Item>> {
    match item {
        Ok((key, value)) => {
            let id = Item::deser_key(&key);

            let value = Item::deser_owned(value);
            Some(Entry {
                key: id,
                val: value,
            })
        }
        Err(e) => {
            error!(%e);
            None
        }
    }
}

#[inline]
fn entry_map<Item: Record<Value = Slice>>(item: fjall::Result<KeyValue>) -> DbResult<Entry<Item>> {
    item.map_err(DbError::from).map(|item| {
        let (key, value) = item;
        let id = Item::deser_key(&key);
        let val = Item::deser_owned(value);
        Entry { key: id, val }
    })
}

#[inline]
fn entry_map_with_raw<Item: Record<Value = Slice>>(
    item: fjall::Result<KeyValue>,
) -> DbResult<ItemWithRaw<Item>> {
    item.map_err(DbError::from).map(|item| {
        let (key, value) = item;
        let id = Item::deser_key(&key);
        let val = Item::deser(&value);
        (key, value, Entry { key: id, val })
    })
}
