//! Storage layer for AiFastDb
//!
//! Provides persistent storage for vectors, documents, and graphs
//! using memory-mapped files for efficient I/O.
//!
//! # Modules
//!
//! - `backend`: Unified `StorageBackend` trait for pluggable storage engines
//! - `document`: Document storage with JSONL persistence
//! - `graph`: Knowledge graph storage
//! - `collection`: Multi-collection management
//! - `mmap`: Memory-mapped file storage
//! - `concurrent`: High-concurrency write support
//! - `wal`: Write-ahead logging for durability
//! - `lance`: Lance columnar storage backend (requires `lance-storage` feature)

pub mod backend;
pub mod filter_expr;
pub mod vector_backend;
pub mod vector_search_engine;
pub mod mmap;
pub mod document;
pub mod document_enhanced;
pub mod graph;
pub mod collection;
pub mod concurrent;
pub mod wal;
pub mod concurrent_store;
pub mod legacy_backend;

#[cfg(feature = "lance-storage")]
pub mod lance;

pub use backend::{
    StorageBackend, StorageError, StorageResult, QueryFilter,
    MetadataFilter, SortField, SortOrder, SemanticGateFilter,
    NestedFieldFilter, FilterOp, resolve_json_path,
};
pub use filter_expr::{FilterExpr, FilterField, FilterValue};
pub use vector_backend::{
    VectorBackend, VectorSearchResult, VectorIndexConfig,
    VectorIndexType, VectorDistanceMetric, MmapVectorBackend,
    QuantizationStrategy, VectorIndexInfo,
    MultiVectorBackend, VectorColumnConfig, MultiVectorFusion,
};
pub use vector_search_engine::{VectorSearchEngine, VectorSearchStrategy};
pub use mmap::MmapStorage;
pub use document::DocumentStore;
pub use document_enhanced::{EnhancedDocumentStore, EnhancedStoreConfig};
pub use graph::GraphStore;
pub use collection::{Collection, CollectionStore};
pub use legacy_backend::LegacyStorageBackend;

#[cfg(feature = "lance-storage")]
pub use lance::{LanceStorageBackend, LanceVectorBackend};

use crate::types::config::{StorageConfig, StorageType};

/// Create a `StorageBackend` from configuration.
///
/// Returns a `Box<dyn StorageBackend>` backed by either:
/// - **Legacy** (JSONL) — always available
/// - **Lance** (columnar) — requires `lance-storage` feature
///
/// # Examples
///
/// ```no_run
/// use aifastdb_core::types::config::StorageConfig;
/// use aifastdb_core::storage::create_storage_backend;
///
/// let config = StorageConfig::default();
/// let backend = create_storage_backend(&config).unwrap();
/// println!("Using backend: {}", backend.backend_name());
/// ```
pub fn create_storage_backend(
    config: &StorageConfig,
) -> StorageResult<Box<dyn StorageBackend>> {
    match config.backend {
        StorageType::Legacy => {
            let path = std::path::Path::new(&config.path).join("documents.jsonl");
            let backend = LegacyStorageBackend::new(path)?;
            Ok(Box::new(backend))
        }
        StorageType::Lance => {
            #[cfg(feature = "lance-storage")]
            {
                let lance_path = std::path::Path::new(&config.path).join("memories.lance");
                let mut lance_config = lance::lance_backend::LanceConfig::new(lance_path);
                if let Some(dim) = config.embedding_dim {
                    lance_config = lance_config.with_embedding_dim(dim);
                }
                lance_config = lance_config.with_write_batch_size(config.lance_write_batch_size);
                let backend = lance::lance_backend::LanceStorageBackend::open(lance_config)?;
                Ok(Box::new(backend))
            }
            #[cfg(not(feature = "lance-storage"))]
            {
                Err(StorageError::Backend(
                    "Lance storage backend requires the 'lance-storage' feature to be enabled. \
                     Add `features = [\"lance-storage\"]` to your Cargo.toml dependency."
                        .to_string(),
                ))
            }
        }
    }
}

// Re-export concurrent types for convenience
pub use concurrent::{
    WriteMetrics, MetricsSnapshot,
    WriteQueue, WriteQueueConfig,
    BatchAggregator, BatchConfig,
    BackpressureController, BackpressureConfig,
    ShardRouter, ShardRouterConfig, ShardStrategy,
    WriteShard, WriteShardConfig,
};

// Re-export WAL types
pub use wal::{
    WALWriter, WALWriterConfig, SyncMode,
    WALReader, WALIterator,
    WALCompactor, CompactorConfig,
    WALEntry, WALHeader, WALOperation,
};

// Re-export concurrent store
pub use concurrent_store::{
    ConcurrentDocumentStore, ConcurrentStoreConfig, ConcurrentStoreError,
    RecoveryResult,
};
