//! AiFastDb Core - High-performance AI-friendly database engine
//!
//! This crate provides the core functionality for AiFastDb:
//! - HNSW vector index for approximate nearest neighbor search
//! - Memory-mapped storage for efficient I/O
//! - Hybrid query engine combining vector, text, and metadata search
//! - Knowledge graph storage and traversal
//! - Social graph module for social network analysis
//! - Perception module for embedding generation and reasoning
//! - Semantic module for deduplication and conflict detection
//! - Triggers module for write pipeline hooks

pub mod types;
pub mod vector;
pub mod storage;
pub mod query;
pub mod perception;
pub mod semantic;
pub mod triggers;
pub mod social;
pub mod search;

#[cfg(feature = "federation")]
pub mod federation;

#[cfg(feature = "sql-engine")]
pub mod sql;

/// 统一 GPU 设备抽象层 (Phase-61)
///
/// 所有 GPU/计算功能共享此单一设备检测与选择层。
/// 在无 `candle` feature 时仍可编译（所有功能安全降级到 CPU）。
pub mod device;

/// RAG Pipeline — 对话式数据库查询 (Phase-72)
///
/// Retrieval-Augmented Generation: 向量检索 + 全文搜索 + Reranker + LLM 生成
/// - Retriever trait: 混合检索接口
/// - Generator trait: LLM 生成接口 (MicroGPT / External API)
/// - ContextAssembler trait: 上下文组装 + token 预算裁剪
pub mod rag;

/// MicroGPT Engine — 数据库原生 GPT 推理+训练引擎 (Phase-68)
///
/// Decoder-only Transformer 架构，与 BriLLM SiFu 引擎互补共存。
/// - 推理: `MicroGpt::forward()` / `generate()` / `generate_text()`
/// - 训练: `GptTrainer::train_step()` / `MicroGpt::train_on_text()`
/// - GPU: 通过 `DeviceSelector` 自动选择 CUDA/Metal/CPU
pub mod gpt;

/// Tree Index — 树状文档索引 (Phase-90)
///
/// 基于 PageIndex 算法原理的树结构文档索引，支持 Markdown 解析、
/// 树精简 (thinning)、SocialGraphV2 持久化存储、PageIndex JSON 导入导出。
pub mod tree_index;

/// Plugin Framework — 通用插件基础设施 (Phase-92)
///
/// 进程隔离的 HTTP 插件系统：注册/发现/健康检查/优雅降级。
/// - PluginManifest: 插件元数据声明
/// - PluginManager: 生命周期管理 + 安全调用
/// - .plugins.json: 配置文件格式 + 热重载
pub mod plugin;

/// LLM Gateway — 统一大模型对话网关 (Phase-78 ~ Phase-81)
///
/// 多 Provider 支持（OpenAI/DeepSeek/Ollama/Gemini/Anthropic 等），
/// 统一 Client Trait、流式 SSE、Provider Router + Failover + 健康检查。
/// - Provider/Model 数据模型 + 动态注册
/// - 统一 LlmClient trait + StreamEvent
/// - 品牌路由 + 自动故障转移 + 负载均衡
#[cfg(feature = "llm-gateway")]
pub mod llm;

#[cfg(feature = "gpu-index")]
pub mod gpu;

// Re-export commonly used types
pub use types::{
    config::{HNSWConfig, StorageConfig, StorageType, AiFastDbConfig},
    memory::{MemoryNode, ContentType, validate_id, is_valid_id, InvalidIdError},
    graph::{Entity, Relation},
    collection::{
        CollectionConfig, CollectionMetadata, DatabaseMetadata, DEFAULT_COLLECTION,
        ForeignKeyConfig, OnDeleteAction, PopulateConfig,
    },
};

pub use vector::hnsw::HNSWIndex;
pub use storage::mmap::MmapStorage;
pub use storage::collection::{
    Collection, CollectionStore,
    ForeignKeyError, ForeignKeyValidationResult, CascadeDeleteResult,
};
pub use storage::{
    StorageBackend, StorageError, StorageResult, QueryFilter,
    MetadataFilter, SortField, SortOrder,
    LegacyStorageBackend, create_storage_backend,
    // Vector backend
    VectorBackend, VectorSearchResult, VectorIndexConfig,
    VectorIndexType, VectorDistanceMetric, MmapVectorBackend,
    // Vector search engine
    VectorSearchEngine, VectorSearchStrategy,
};

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

// Phase-74: OCC (Optimistic Concurrency Control) types
#[cfg(feature = "lance-storage")]
pub use storage::lance::lance_backend::{OCCConfig, OCCMetrics, OCCMetricsSnapshot};

// Phase-75: Stateless Query Node (read-only horizontal scaling)
#[cfg(feature = "lance-storage")]
pub use storage::lance::query_node::{QueryNode, QueryNodeConfig, NodeRole, NodeStatus, QueryNodeMetricsSnapshot};

// Multimodal types
pub use types::multimodal::{
    MultimodalRecord, MediaType, MediaMetadata, MultimodalConfig,
    MultimodalBackend, CrossModalSearchResult, CrossModalQuery,
    // Phase-60: native vector column support
    MultimodalVectorConfig, VectorColumnDef, MultimodalIndexInfo,
};
pub use query::hybrid::HybridQueryEngine;
pub use query::multi_collection::MultiCollectionQueryEngine;

// Perception module exports
pub use perception::{
    PerceptionConfig, PerceptionModuleConfig, ReasoningConfig,
    PerceptionEngine, ReasoningEngine, Modality,
    PerceptionError, ReasoningError,
    create_perception_engine, create_reasoning_engine, create_composite_engine,
};

// Semantic module exports
pub use semantic::{
    SemanticChecker, SemanticCheckerConfig, CheckResult,
    DuplicateCandidate, ConflictCandidate, DuplicateReason, ConflictType,
    DuplicateAction, ConflictAction, SemanticError,
};

// Triggers module exports
pub use triggers::{
    TriggerRegistry, RustTrigger, TriggerPhase, TriggerContext, TriggerResult,
    TriggerConfig, TriggerPriority, TriggerError, DeferredAction, NeighborInfo,
    SimilarityTrigger, ImportanceAdjustTrigger, KnowledgeGraphTrigger,
    ConsolidationTrigger, TimestampValidationTrigger, create_default_registry,
};

// Full-text search module exports
pub use search::{
    FullTextIndex, FTSQuery, FTSQueryMode, FTSSearchResult,
    FTSDocument, FTSConfig, FTSError, FTSResult,
    // Phase-73 additions
    TokenizerLanguage, SynonymMap, SynonymEntry, SynonymFile,
};
#[cfg(feature = "full-text-search")]
pub use search::TantivyFullTextIndex;

// Social graph module exports
pub use social::{
    // Types
    PersonInput, PersonFilter, FriendConfig, TagInput,
    ItemInput, SharedItemResult, ItemMatchResult, ItemMatchDetail,
    AttributeInput, AttributeMatchConfig, SharedAttributeResult,
    SharedAttributeDetail, AttributeMatchResult, CompatibilityResult,
    PathResult, AllPathsResult, PathOptions,
    DegreeContacts, RelationshipStrength, SuggestionReason,
    ConnectionSuggestion, SuggestionConfig, NetworkStats,
    // Core components (V2 - High Concurrency)
    SocialStoreV2, SocialStoreV2Config, PerformanceSummary,
    PathFinder, NetworkAnalyzer, ItemMatcher, AttributeMatcher,
};

// Federation module exports (v2.0 - Heterogeneous Storage)
#[cfg(feature = "federation")]
pub use federation::{
    // Core types
    Federation, FederationConfig, FederationError,
    Store, StoreType, Record, WriteOp, WriteResult,
    UniversalQuery, QueryResult, CrossDbQuery,
    // Adapters
    GraphStoreAdapter, DocumentStoreAdapter,
    // Components
    CrossDbIndex, QueryPlanner, TransactionCoordinator,
    TransactionState, FederatedTransaction,
};
#[cfg(all(feature = "federation", feature = "lance-storage"))]
pub use federation::LanceStoreAdapter;

// SQL query engine exports (DataFusion integration)
#[cfg(feature = "sql-engine")]
pub use sql::{
    SqlQueryEngine, AifastDbSessionContext, LanceTableProvider,
    VectorDistanceUdf, register_all_udfs,
};

// Device abstraction layer exports (Phase-61)
pub use device::{
    DevicePreference, GpuAccelConfig, DeviceSelector,
    WorkloadHint, DeviceAvailability,
    GpuFallbackEvent, FallbackReason,
};

// Plugin Framework exports (Phase-92)
pub use plugin::{
    PluginManager, PluginManagerConfig,
    PluginManifest, PluginInfo, PluginStatus, PluginType, PluginCapability,
    PluginError, PluginResult, PluginCallOptions,
    PluginsConfig, PluginEntry, PluginConfigWatcher,
    HealthResponse as PluginHealthResponse,
    IndexRequest as PluginIndexRequest, IndexResponse as PluginIndexResponse,
    ProcessRequest as PluginProcessRequest, ProcessResponse as PluginProcessResponse,
};

// RAG Pipeline exports (Phase-72)
pub use rag::{
    RagConfig, ChatMessage, ChatRole, ChatSession,
    RetrievalResult, SourceReference, RagResponse, RagTokenUsage,
    Retriever, Generator, ContextAssembler,
    HybridRetriever, DefaultContextAssembler,
    RagError, RagResult,
};

// MicroGPT Engine exports (Phase-68)
pub use gpt::GptConfig;
#[cfg(feature = "candle")]
pub use gpt::{
    MicroGpt, GptTrainer, TrainConfig, TrainStepResult,
    GenerateConfig, TrainingReport,
    TokenizerManager, TokenizerType,
};

// LLM Gateway exports (Phase-78)
#[cfg(feature = "llm-gateway")]
pub use llm::{
    // Provider types
    LlmProvider, ProviderBrand, ProviderProtocol, ProviderStatus,
    ProviderCapabilities, RateLimit,
    // Model types
    LlmModel, ModelStatus, ModelCapabilities, ModelPricing,
    ModelDefaultConfig,
    // Chat types
    ChatConfig, ChatResponse, ToolDefinition, FunctionDefinition,
    ToolCall, TokenUsage, FinishReason,
    // Stream types
    StreamEvent, AudioFormat,
    // Error types
    LlmError, LlmResult,
    // Client types
    LlmClient, LlmMessage, MessageRole, ContentPart,
    // Store
    LlmStore,
    // Router & Factory
    ProviderRouter, RoutingStrategy, LlmClientFactory,
    // Conversation types (Phase-79)
    LlmConversation, ConversationConfig, StoredMessage,
    Attachment, MessageStatus, ConversationQuery, MessageQuery, UsageStats,
    ConversationManager,
    // Stream Engine (Phase-80)
    SseEvent, stream_event_to_sse, parse_sse_event,
    // Prompt Template (Phase-81)
    PromptTemplate, PromptTemplateStore,
    // Tool Executor (Phase-83)
    ToolExecutor, ToolMetadata, ToolRegistry, ToolResult,
    // Tool Call Loop (Phase-83)
    ToolCallLoop, ToolCallLoopResult, ToolCallRound, ToolCallResult,
    // Memory (Phase-84)
    MemoryManager, MemoryConfig, MemoryContext, MemoryLayer, InMemoryLayer,
    // NL-to-SQL Engine (Phase-85)
    NlToSqlEngine, NlToSqlConfig, NlQueryResult, SqlAttempt,
    SchemaContext, TableInfo, ColumnInfo,
    SqlSafetyResult, validate_sql_safety,
    // Agent Engine (Phase-87)
    AgentEngine, AgentConfig, AgentResult, AgentStep, AgentStepType,
    AgentPlan, PlanStep, AgentContext, AgentToolResult,
    AgentTemplate, AgentTemplateConfig, AgentResourceLimits, AgentResourceUsage,
    get_builtin_template, list_builtin_templates, apply_template,
};

/// AiFastDb version
pub const VERSION: &str = env!("CARGO_PKG_VERSION");

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

    #[test]
    fn test_version() {
        assert!(!VERSION.is_empty());
    }
}
