// {{ display_name }} MCP server — generated by mcpify. Do not hand-edit.
//
// Single data-access layer against mcp_store.db — both the relational
// `endpoints` table and the `semantic_endpoints` vec0 virtual table
// (REQ-2.4.1's single-store consolidation). Mirrors the shape of
// mcpify's own src/db/open.rs almost directly, since both the generator
// and the generated project use the identical rusqlite+sqlite-vec crate
// pair. Unlike mcpify's own src/db/schema.rs, this module never creates
// tables — mcpify's shared pipeline (Story 5/6) already wrote
// mcp_store.db's schema before any generated code runs.

use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::sync::{Mutex, Once, OnceLock};
use std::time::Duration;

use anyhow::{Context, Result};
use rusqlite::backup::Backup;
use rusqlite::{Connection, OpenFlags, Row};
use serde::Serialize;

static REGISTER_VEC_EXTENSION: Once = Once::new();

// mcpify:versions:begin
pub const VERSION_STORE_FILES: &[(&str, &str)] = &[
{%- for v in version_entries %}
    ("{{ v.label }}", "{{ v.db_file }}"),
{%- endfor %}
];

// Every `.db` this crate supports, embedded into the compiled binary
// itself via `include_bytes!` — mirrors how `validator.rs` already
// embeds each version's schema, so this crate never needs its `.db`
// files to exist anywhere on disk after `cargo install`.
const VERSION_STORE_BYTES: &[(&str, &[u8])] = &[
{%- for v in version_entries %}
    ("{{ v.label }}", include_bytes!("../../{{ v.db_file }}")),
{%- endfor %}
];
// mcpify:versions:end

/// Resolves the active `api_version` (from the config cascade) to its
/// store file. Every `.db` this crate supports is embedded into the
/// compiled binary via `include_bytes!` (`VERSION_STORE_BYTES`) exactly
/// like `validator.rs` embeds each version's schema — there is no
/// filesystem fallback chain to reason about, and this crate never
/// depends on any particular `.db` file existing anywhere on disk after
/// `cargo install`. The one difference from a schema lookup: SQLite
/// needs a real file to open a `Connection` against (unlike a `&[u8]`
/// JSON schema, read directly from memory), so this extracts the
/// embedded bytes to a fixed path in the OS temp dir on every call —
/// cheap, since it only runs once per process start, and it means a
/// rebuilt binary with different embedded bytes (a `populate_embeddings`
/// re-run, an `add-version` update) can never be shadowed by a stale
/// leftover from a previous install at that same path.
pub fn resolve_store_path(api_version: &str) -> Result<PathBuf> {
    let file = VERSION_STORE_FILES
        .iter()
        .find(|(label, _)| *label == api_version)
        .map(|(_, file)| *file)
        .with_context(|| format!("unknown api_version '{api_version}' — run the 'versions' command to see what's available"))?;
    let bytes = VERSION_STORE_BYTES
        .iter()
        .find(|(label, _)| *label == api_version)
        .map(|(_, bytes)| *bytes)
        .with_context(|| format!("no embedded store data for api_version '{api_version}'"))?;

    let mut dir = std::env::temp_dir();
    dir.push(concat!(env!("CARGO_PKG_NAME"), "-store"));
    std::fs::create_dir_all(&dir)
        .with_context(|| format!("failed to create temp dir '{}'", dir.display()))?;

    let path = dir.join(file);
    // Always (re)writes rather than skipping when the path already
    // exists: the extraction path doesn't vary by build, so a stale copy
    // from a previous install (older embedded bytes, e.g. before a
    // `populate_embeddings` re-run or an `add-version` update) would
    // otherwise linger forever, silently serving outdated data. The
    // write is cheap — this runs once per process start, not per query.
    std::fs::write(&path, bytes).with_context(|| {
        format!(
            "failed to extract embedded store data to '{}'",
            path.display()
        )
    })?;

    Ok(path)
}

const ENDPOINT_COLUMNS: &str = "operation_id, path, method, summary, description, input_schema, output_schema, auth_scheme_ref";

/// Registers the `sqlite-vec` extension once per process, via
/// `sqlite3_auto_extension` — matching the pattern the `sqlite-vec` crate
/// itself documents for `rusqlite`.
fn register_vec_extension() {
    REGISTER_VEC_EXTENSION.call_once(|| unsafe {
        #[allow(clippy::missing_transmute_annotations)]
        rusqlite::ffi::sqlite3_auto_extension(Some(std::mem::transmute(
            sqlite_vec::sqlite3_vec_init as *const (),
        )));
    });
}

/// Opens `mcp_store.db` read-only: this crate's binaries only ever read
/// it, except `{{ project_name }}-populate-embeddings` (a separate `[[bin]]`), which uses
/// `open_store_read_write` instead.
pub fn open_store(path: &Path) -> Result<Connection> {
    register_vec_extension();
    Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_ONLY)
        .with_context(|| format!("failed to open '{}'", path.display()))
}

/// Read-write counterpart to `open_store` — for `bin/populate_embeddings.rs`,
/// the one binary that actually writes to `mcp_store.db` (backfilling
/// `semantic_endpoints`, whose table every other caller only ever reads
/// from).
pub fn open_store_read_write(path: &Path) -> Result<Connection> {
    register_vec_extension();
    Connection::open_with_flags(path, OpenFlags::SQLITE_OPEN_READ_WRITE)
        .with_context(|| format!("failed to open '{}'", path.display()))
}

/// Returns a process-wide, in-memory-backed connection for `api_version`:
/// on first access, opens the on-disk file read-only via `open_store`,
/// copies its entire contents into a fresh `:memory:` connection (via
/// SQLite's backup API), then drops the on-disk connection immediately —
/// so its file handle/lock is held only for that brief copy, not for the
/// process's lifetime. This means an external process (a fresh
/// `{{ project_name }}-populate-embeddings` run, a deployment replacing the file) can update
/// `mcp_store.db` without hitting "database is locked" against a live
/// server, at the cost of the running process only picking up such an
/// update on its next restart.
///
/// Returns the connection behind a `Mutex` rather than handing it out
/// directly: callers must finish with the guard (and drop it) *before*
/// any `.await` — `rusqlite::Connection` isn't `Sync`, so holding the
/// guard across an await point would make the enclosing future
/// non-`Send`, the same constraint `core/mcp_server.rs`'s tool handlers
/// already respect for a plain `Connection`.
pub fn cached_store_connection(api_version: &str) -> Result<&'static Mutex<Connection>> {
    let path = resolve_store_path(api_version)?;
    cached_in_memory_connection(api_version, &path)
}

/// Does the actual work for `cached_store_connection`, taking an explicit
/// path (rather than resolving one from `api_version` itself) so it's
/// testable against an arbitrary tempdir path — `cache_key` and `path`
/// are separate parameters because two different `api_version`s should
/// never collide in the process-wide cache even if (hypothetically) they
/// resolved to the same file.
fn cached_in_memory_connection(cache_key: &str, path: &Path) -> Result<&'static Mutex<Connection>> {
    static CACHE: OnceLock<Mutex<HashMap<String, &'static Mutex<Connection>>>> = OnceLock::new();
    let cache = CACHE.get_or_init(|| Mutex::new(HashMap::new()));

    if let Some(conn) = cache.lock().unwrap().get(cache_key) {
        return Ok(conn);
    }

    let disk_conn = open_store(path)?;
    let mut mem_conn = Connection::open_in_memory()
        .context("failed to open an in-memory SQLite connection")?;
    Backup::new(&disk_conn, &mut mem_conn)
        .context("failed to start SQLite backup into memory")?
        .run_to_completion(i32::MAX, Duration::from_millis(0), None)
        .with_context(|| format!("failed to back up '{}' into memory", path.display()))?;
    drop(disk_conn);

    let leaked: &'static Mutex<Connection> = Box::leak(Box::new(Mutex::new(mem_conn)));
    let mut cache = cache.lock().unwrap();
    Ok(*cache.entry(cache_key.to_string()).or_insert(leaked))
}

#[derive(Debug, Clone, Serialize)]
pub struct EndpointRecord {
    pub operation_id: String,
    pub path: String,
    pub method: String,
    pub summary: Option<String>,
    pub description: Option<String>,
    pub input_schema: serde_json::Value,
    pub output_schema: serde_json::Value,
    pub auth_scheme_ref: Option<String>,
}

fn row_to_endpoint(row: &Row) -> rusqlite::Result<EndpointRecord> {
    let input_schema: String = row.get(5)?;
    let output_schema: String = row.get(6)?;
    Ok(EndpointRecord {
        operation_id: row.get(0)?,
        path: row.get(1)?,
        method: row.get(2)?,
        summary: row.get(3)?,
        description: row.get(4)?,
        input_schema: serde_json::from_str(&input_schema).unwrap_or(serde_json::Value::Null),
        output_schema: serde_json::from_str(&output_schema).unwrap_or(serde_json::Value::Null),
        auth_scheme_ref: row.get(7)?,
    })
}

pub fn get_endpoint(conn: &Connection, operation_id: &str) -> Result<Option<EndpointRecord>> {
    let mut stmt = conn.prepare(&format!(
        "SELECT {ENDPOINT_COLUMNS} FROM endpoints WHERE operation_id = ?1"
    ))?;
    match stmt.query_row([operation_id], row_to_endpoint) {
        Ok(record) => Ok(Some(record)),
        Err(rusqlite::Error::QueryReturnedNoRows) => Ok(None),
        Err(err) => Err(err.into()),
    }
}

pub fn list_endpoints(conn: &Connection) -> Result<Vec<EndpointRecord>> {
    let mut stmt = conn.prepare(&format!("SELECT {ENDPOINT_COLUMNS} FROM endpoints"))?;
    let rows = stmt.query_map([], row_to_endpoint)?;
    Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}

#[derive(Debug, Clone, Serialize)]
pub struct SearchResult {
    pub operation_id: String,
    pub summary: Option<String>,
    pub similarity: f64,
}

/// k-nearest-neighbor search over `semantic_endpoints` (sqlite-vec's
/// documented `MATCH ... AND k = ...` query form). `query_embedding` must
/// come from the same model as the vectors it's compared against — see
/// `services::embedding_service`. Bound as a raw little-endian `f32` blob,
/// the same wire format `bin/populate_embeddings.rs` writes (sqlite-vec
/// accepts either that or a JSON array per-call, independent of how any
/// given row was originally inserted, so this is a consistency choice, not
/// a correctness requirement).
///
/// `similarity` is a simple `1 - distance` transform of sqlite-vec's L2
/// distance, not a true cosine-similarity computation; since embeddings
/// are normalized (unit vectors), L2-distance ordering already matches
/// cosine-similarity ordering, so result *ranking* is correct even though
/// the displayed score is an approximation.
pub fn search_endpoints(
    conn: &Connection,
    query_embedding: &[f32],
    limit: usize,
) -> Result<Vec<SearchResult>> {
    let blob: Vec<u8> = query_embedding
        .iter()
        .flat_map(|value| value.to_le_bytes())
        .collect();

    let mut stmt = conn.prepare(
        "SELECT e.operation_id, e.summary, s.distance
         FROM semantic_endpoints s
         JOIN endpoints e ON e.operation_id = s.operation_id
         WHERE s.embedding MATCH ?1 AND k = ?2
         ORDER BY s.distance",
    )?;
    let rows = stmt.query_map(rusqlite::params![blob, limit], |row| {
        let distance: f64 = row.get(2)?;
        Ok(SearchResult {
            operation_id: row.get(0)?,
            summary: row.get(1)?,
            similarity: 1.0 - distance,
        })
    })?;
    Ok(rows.collect::<rusqlite::Result<Vec<_>>>()?)
}

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

    /// Guards against `VERSION_STORE_FILES` and `VERSION_STORE_BYTES`
    /// silently drifting apart — every `api_version` this crate lists must
    /// resolve to embedded bytes, or `resolve_store_path` fails at runtime
    /// for exactly that version and nothing else, which is easy to miss in
    /// review since the two arrays are edited in different places.
    #[test]
    fn every_version_store_file_has_embedded_bytes() {
        let file_labels: std::collections::HashSet<_> =
            VERSION_STORE_FILES.iter().map(|(label, _)| *label).collect();
        let byte_labels: std::collections::HashSet<_> =
            VERSION_STORE_BYTES.iter().map(|(label, _)| *label).collect();
        assert_eq!(file_labels, byte_labels);
    }

    /// Builds a read-write connection with the same schema mcpify's shared
    /// pipeline writes, and seeds it with one row — real usage never
    /// creates this schema (mcpify already wrote it before any generated
    /// code runs), so this setup is test-only fixture, not production
    /// code these tests exercise.
    fn seeded_store(path: &Path) -> Connection {
        unsafe {
            #[allow(clippy::missing_transmute_annotations)]
            rusqlite::ffi::sqlite3_auto_extension(Some(std::mem::transmute(
                sqlite_vec::sqlite3_vec_init as *const (),
            )));
        }
        let conn = Connection::open(path).unwrap();
        conn.execute(
            "CREATE TABLE endpoints (
                operation_id TEXT PRIMARY KEY,
                path TEXT NOT NULL,
                method TEXT NOT NULL,
                summary TEXT,
                description TEXT,
                input_schema TEXT NOT NULL,
                output_schema TEXT NOT NULL,
                auth_scheme_ref TEXT
            )",
            [],
        )
        .unwrap();
        conn.execute(
            "CREATE VIRTUAL TABLE semantic_endpoints USING vec0(
                operation_id TEXT PRIMARY KEY,
                embedding FLOAT[4]
            )",
            [],
        )
        .unwrap();
        conn.execute(
            "INSERT INTO endpoints (operation_id, path, method, summary, description, input_schema, output_schema, auth_scheme_ref)
             VALUES ('listWidgets', '/widgets', 'GET', 'List widgets', NULL, '{}', '[]', NULL)",
            [],
        )
        .unwrap();
        let embedding: Vec<u8> = [1.0f32, 0.0, 0.0, 0.0]
            .iter()
            .flat_map(|v| v.to_le_bytes())
            .collect();
        conn.execute(
            "INSERT INTO semantic_endpoints (operation_id, embedding) VALUES ('listWidgets', ?1)",
            rusqlite::params![embedding],
        )
        .unwrap();
        conn
    }

    #[test]
    fn get_endpoint_returns_a_seeded_row() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let store = open_store(&path).unwrap();
        let endpoint = get_endpoint(&store, "listWidgets").unwrap().unwrap();
        assert_eq!(endpoint.path, "/widgets");
        assert_eq!(endpoint.method, "GET");
        assert_eq!(endpoint.summary.as_deref(), Some("List widgets"));
    }

    #[test]
    fn get_endpoint_returns_none_for_an_unknown_operation() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let store = open_store(&path).unwrap();
        assert!(get_endpoint(&store, "unknownOp").unwrap().is_none());
    }

    #[test]
    fn list_endpoints_returns_every_row() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let store = open_store(&path).unwrap();
        let endpoints = list_endpoints(&store).unwrap();
        assert_eq!(endpoints.len(), 1);
        assert_eq!(endpoints[0].operation_id, "listWidgets");
    }

    #[test]
    fn search_endpoints_finds_the_nearest_neighbor() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let store = open_store(&path).unwrap();
        let results = search_endpoints(&store, &[1.0, 0.0, 0.0, 0.0], 5).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].operation_id, "listWidgets");
        assert!(results[0].similarity > 0.99);
    }

    #[test]
    fn cached_in_memory_connection_serves_seeded_data() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let cached = cached_in_memory_connection("cached-serves-seeded-data", &path).unwrap();
        let endpoint = get_endpoint(&cached.lock().unwrap(), "listWidgets")
            .unwrap()
            .unwrap();
        assert_eq!(endpoint.path, "/widgets");

        // vec0 search must also work against the in-memory copy —
        // `register_vec_extension`'s `sqlite3_auto_extension` applies
        // process-wide, so it isn't specific to file-backed connections.
        let results = search_endpoints(&cached.lock().unwrap(), &[1.0, 0.0, 0.0, 0.0], 5).unwrap();
        assert_eq!(results.len(), 1);
        assert_eq!(results[0].operation_id, "listWidgets");
    }

    #[test]
    fn cached_in_memory_connection_holds_no_lingering_lock_on_the_disk_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let cached =
            cached_in_memory_connection("cached-releases-disk-handle", &path).unwrap();

        // If the disk connection were still open, removing the file out
        // from under it would be the exact failure mode this fix exists
        // to avoid.
        std::fs::remove_file(&path).unwrap();

        let endpoint = get_endpoint(&cached.lock().unwrap(), "listWidgets")
            .unwrap()
            .unwrap();
        assert_eq!(endpoint.path, "/widgets");
    }

    #[test]
    fn cached_in_memory_connection_reuses_the_same_connection_for_the_same_key() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("mcp_store.db");
        let _conn = seeded_store(&path);

        let first = cached_in_memory_connection("cached-reuses-same-key", &path).unwrap()
            as *const Mutex<Connection>;
        let second = cached_in_memory_connection("cached-reuses-same-key", &path).unwrap()
            as *const Mutex<Connection>;
        assert_eq!(first, second, "expected the same cached connection, not a fresh backup");
    }
}
