//! `MemoryPgvector` — convenience factory wrapping the `LongTermMemory`
//! handle in an `Arc<dyn …>` ready for `AgentContext`.

use crate::client::{PgvectorConfig, PgvectorHandle};
use crate::embedder::{DummyEmbedder, Embedder};
use crate::long_term::PgvectorLongTerm;
use klieo_core::error::MemoryError;
use klieo_core::memory::LongTermMemory;
use std::sync::Arc;

/// Factory bundle returned by [`MemoryPgvector::new`].
#[non_exhaustive]
pub struct MemoryPgvector {
    /// Trait-object view for `AgentContext`; the same instance as
    /// [`Self::pgvector_long_term`] (use this unless you need the concrete type).
    pub long_term: Arc<dyn LongTermMemory>,
    /// Concrete [`PgvectorLongTerm`] handle. `FilterableLongTermMemory` lives
    /// in `klieo-memory-graph` and cannot ride the `LongTermMemory` trait
    /// object, so the GraphRAG composer needs the concrete type. Both fields
    /// point at the same instance.
    pub pgvector_long_term: Arc<PgvectorLongTerm>,
}

impl MemoryPgvector {
    /// Capability-shaped default — connect with [`DummyEmbedder`] and default
    /// [`PgvectorConfig`] (table prefix `klieo_facts`, embedder id `default`).
    ///
    /// Use [`Self::new`] for a real embedder or a non-default config.
    pub async fn connect(url: impl Into<String>) -> Result<Self, MemoryError> {
        Self::new(PgvectorConfig::new(url), Arc::new(DummyEmbedder)).await
    }

    /// Connect to Postgres and return a ready-to-use handle. The table is
    /// provisioned lazily on the first `remember`, so concurrent process
    /// starts don't race on DDL.
    pub async fn new(
        cfg: PgvectorConfig,
        embedder: Arc<dyn Embedder>,
    ) -> Result<Self, MemoryError> {
        let embedder_id = cfg.embedder_id().to_string();
        let handle = PgvectorHandle::connect(&cfg).await?;
        let pgvector_long_term = Arc::new(PgvectorLongTerm::new(handle, embedder, embedder_id));
        let long_term: Arc<dyn LongTermMemory> = pgvector_long_term.clone();
        Ok(Self {
            long_term,
            pgvector_long_term,
        })
    }
}
