// Copyright 2024 The Drasi Authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use std::sync::Arc;

use crate::IndexDb;
use async_trait::async_trait;
use drasi_core::{
    interface::{ElementArchiveIndex, ElementStream, IndexError},
    models::{Element, ElementReference, ElementTimestamp, TimestampBound, TimestampRange},
};
use prost::{bytes::Bytes, Message};
use rocksdb::{Options, SliceTransform, Transaction};
use tokio::task;

use crate::{
    element_index::RocksDbElementIndex,
    storage_models::{StoredElement, StoredElementContainer},
};

use super::{Context, ReferenceHash};

pub const ARCHIVE_CF: &str = "archive";

#[async_trait]
impl ElementArchiveIndex for RocksDbElementIndex {
    async fn get_element_as_at(
        &self,
        element_ref: &ElementReference,
        time: ElementTimestamp,
    ) -> Result<Option<Arc<Element>>, IndexError> {
        if !self.context.options.archive_enabled {
            return Err(IndexError::ArchiveNotEnabled);
        }
        let context = self.context.clone();
        let element_key = super::hash_element_ref(element_ref);
        let mut key = element_key.to_vec();
        key.extend_from_slice(&time.to_be_bytes());

        let task = task::spawn_blocking(move || {
            let archive_cf = match context.db.cf_handle(ARCHIVE_CF) {
                Some(cf) => cf,
                None => return Err(IndexError::ArchiveNotEnabled),
            };
            context.session_state.with_txn(|txn| {
                let mut iter = txn
                    .iterator_cf(
                        &archive_cf,
                        rocksdb::IteratorMode::From(&key, rocksdb::Direction::Reverse),
                    )
                    .take(1);
                if let Some(item) = iter.next() {
                    match item {
                        Ok((_, value)) => Ok(Some(value)),
                        Err(err) => Err(IndexError::other(err)),
                    }
                } else {
                    Ok(None)
                }
            })
        });

        match task.await {
            Ok(Ok(Some(data))) => {
                let stored_element: StoredElement =
                    match StoredElementContainer::decode(data.as_ref()) {
                        Ok(container) => match container.element {
                            Some(element) => element,
                            None => return Err(IndexError::CorruptedData),
                        },
                        Err(e) => return Err(IndexError::other(e)),
                    };
                Ok(Some(Arc::new(stored_element.into())))
            }
            Ok(Ok(None)) => Ok(None),
            Ok(Err(e)) => Err(e),
            Err(e) => Err(IndexError::other(e)),
        }
    }

    #[allow(clippy::unwrap_used)]
    async fn get_element_versions(
        &self,
        element_ref: &ElementReference,
        range: TimestampRange<ElementTimestamp>,
    ) -> Result<ElementStream, IndexError> {
        if !self.context.options.archive_enabled {
            return Err(IndexError::ArchiveNotEnabled);
        }
        let context = self.context.clone();
        let element_key = super::hash_element_ref(element_ref);

        let from = range.from;
        let from_timestamp = match from {
            TimestampBound::Included(from) => from,
            TimestampBound::StartFromPrevious(from) => {
                let context = context.clone();
                let task = task::spawn_blocking(move || {
                    let archive_cf = match context.db.cf_handle(ARCHIVE_CF) {
                        Some(cf) => cf,
                        None => return Err(IndexError::ArchiveNotEnabled),
                    };
                    let mut start_key = element_key.clone().to_vec();
                    start_key.extend_from_slice(&from.to_be_bytes());
                    context.session_state.with_txn(|txn| {
                        let mut iter = txn
                            .iterator_cf(
                                &archive_cf,
                                rocksdb::IteratorMode::From(
                                    &start_key,
                                    rocksdb::Direction::Reverse,
                                ),
                            )
                            .take(1);
                        if let Some(item) = iter.next() {
                            match item {
                                Ok((key, _)) => {
                                    let ts = match key.get(16..24) {
                                        // last 8 bytes is the timestamp
                                        Some(v) => u64::from_be_bytes(v.try_into().unwrap()),
                                        None => 0,
                                    };
                                    Ok(ts)
                                }
                                Err(err) => Err(IndexError::other(err)),
                            }
                        } else {
                            Ok(0)
                        }
                    })
                });

                match task.await {
                    Ok(Ok(data)) => data,
                    Ok(Err(e)) => return Err(e),
                    Err(e) => return Err(IndexError::other(e)),
                }
            }
        };
        let to = range.to;
        let mut start_key = element_key.to_vec();

        let task = task::spawn_blocking(move || {
            start_key.extend_from_slice(&from_timestamp.to_be_bytes());
            let archive_cf = match context.db.cf_handle(ARCHIVE_CF) {
                Some(cf) => cf,
                None => return Err(IndexError::ArchiveNotEnabled),
            };
            context.session_state.with_txn(|txn| {
                let mut results: Vec<Result<Arc<Element>, IndexError>> = Vec::new();
                for item in txn.iterator_cf(
                    &archive_cf,
                    rocksdb::IteratorMode::From(&start_key, rocksdb::Direction::Forward),
                ) {
                    match item {
                        Ok((key, data)) => {
                            if !key.starts_with(&element_key) {
                                break;
                            }
                            let ts = match key.get(16..24) {
                                Some(v) => u64::from_be_bytes(v.try_into().unwrap()),
                                None => {
                                    results.push(Err(IndexError::CorruptedData));
                                    break;
                                }
                            };

                            if ts > to {
                                break;
                            }

                            let stored_element: StoredElement =
                                match StoredElementContainer::decode(data.as_ref()) {
                                    Ok(container) => match container.element {
                                        Some(element) => element,
                                        None => continue,
                                    },
                                    Err(e) => {
                                        results.push(Err(IndexError::other(e)));
                                        break;
                                    }
                                };
                            let element: Element = stored_element.into();
                            results.push(Ok(Arc::new(element)));
                        }
                        Err(e) => results.push(Err(IndexError::other(e))),
                    }
                }
                Ok(results)
            })
        });

        let results = match task.await {
            Ok(result) => result?,
            Err(e) => return Err(IndexError::other(e)),
        };

        Ok(Box::pin(futures::stream::iter(results)))
    }

    async fn clear(&self) -> Result<(), IndexError> {
        let context = self.context.clone();

        let task = task::spawn_blocking(move || {
            match context.db.drop_cf(ARCHIVE_CF) {
                Ok(()) => {}
                Err(err) => {
                    let msg = err.to_string();
                    if msg.contains("Invalid column family") {
                        // Column family doesn't exist — nothing to clear
                        return Ok(());
                    }
                    return Err(IndexError::other(err));
                }
            }
            if let Err(err) = context.db.create_cf(ARCHIVE_CF, &get_archive_cf_options()) {
                return Err(IndexError::other(err));
            }
            Ok(())
        });

        task.await.expect("Failed to clear archive")
    }
}

pub fn insert_archive(
    context: Arc<Context>,
    txn: &Transaction<IndexDb>,
    element_key: ReferenceHash,
    element: &Bytes,
    effective_from: u64,
) -> Result<(), IndexError> {
    let archive_cf = context
        .db
        .cf_handle(ARCHIVE_CF)
        .expect("Archive CF not found");
    let mut key = element_key.to_vec();
    key.extend_from_slice(&effective_from.to_be_bytes());
    match txn.put_cf(&archive_cf, key, element) {
        Ok(_) => Ok(()),
        Err(err) => Err(IndexError::other(err)),
    }
}

pub(crate) fn get_archive_cf_options() -> Options {
    let mut opts = Options::default();
    crate::bound_write_buffer_history(&mut opts);
    opts.set_prefix_extractor(SliceTransform::create_fixed_prefix(16));
    opts
}
