import { upsertVectorsResponseSchema, upsertVectorsBodySchema, vectorNamePathParams, createIndexResponseSchema, createIndexBodySchema, queryVectorsResponseSchema, queryVectorsBodySchema, listIndexesResponseSchema, describeIndexResponseSchema, vectorIndexPathParams, deleteIndexResponseSchema, listVectorsResponseSchema, listEmbeddersResponseSchema } from './chunk-RVICRXZF.js';
import { createRoute } from './chunk-PA2BYLKF.js';
import { handleError } from './chunk-P23KBWKB.js';
import { HTTPException } from './chunk-6QWQZI4Q.js';
import { __export } from './chunk-PR4QN5HX.js';
import { EMBEDDING_MODELS } from '@mastra/core/llm';

// src/server/handlers/vector.ts
var vector_exports = {};
__export(vector_exports, {
  CREATE_INDEX_ROUTE: () => CREATE_INDEX_ROUTE,
  DELETE_INDEX_ROUTE: () => DELETE_INDEX_ROUTE,
  DESCRIBE_INDEX_ROUTE: () => DESCRIBE_INDEX_ROUTE,
  LIST_EMBEDDERS_ROUTE: () => LIST_EMBEDDERS_ROUTE,
  LIST_INDEXES_ROUTE: () => LIST_INDEXES_ROUTE,
  LIST_VECTORS_ROUTE: () => LIST_VECTORS_ROUTE,
  QUERY_VECTORS_ROUTE: () => QUERY_VECTORS_ROUTE,
  UPSERT_VECTORS_ROUTE: () => UPSERT_VECTORS_ROUTE,
  createIndex: () => createIndex,
  deleteIndex: () => deleteIndex,
  describeIndex: () => describeIndex,
  listIndexes: () => listIndexes,
  listVectorStores: () => listVectorStores,
  queryVectors: () => queryVectors,
  upsertVectors: () => upsertVectors
});
function getVector(mastra, vectorName) {
  if (!vectorName) {
    throw new HTTPException(400, { message: "Vector name is required" });
  }
  const vector = mastra.getVector(vectorName);
  if (!vector) {
    throw new HTTPException(404, { message: `Vector store ${vectorName} not found` });
  }
  return vector;
}
async function upsertVectors({
  mastra,
  vectorName,
  indexName,
  vectors,
  metadata,
  ids
}) {
  try {
    if (!indexName || !vectors || !Array.isArray(vectors)) {
      throw new HTTPException(400, { message: "Invalid request index. indexName and vectors array are required." });
    }
    const vector = getVector(mastra, vectorName);
    const result = await vector.upsert({ indexName, vectors, metadata, ids });
    return { ids: result };
  } catch (error) {
    return handleError(error, "Error upserting vectors");
  }
}
async function createIndex({
  mastra,
  vectorName,
  indexName,
  dimension,
  metric
}) {
  try {
    if (!indexName || typeof dimension !== "number" || dimension <= 0) {
      throw new HTTPException(400, {
        message: "Invalid request index, indexName and positive dimension number are required."
      });
    }
    if (metric && !["cosine", "euclidean", "dotproduct"].includes(metric)) {
      throw new HTTPException(400, { message: "Invalid metric. Must be one of: cosine, euclidean, dotproduct" });
    }
    const vector = getVector(mastra, vectorName);
    await vector.createIndex({ indexName, dimension, metric });
    return { success: true };
  } catch (error) {
    return handleError(error, "Error creating index");
  }
}
async function queryVectors({
  mastra,
  vectorName,
  indexName,
  queryVector,
  topK,
  filter,
  includeVector
}) {
  try {
    if (!indexName || !queryVector || !Array.isArray(queryVector)) {
      throw new HTTPException(400, { message: "Invalid request query. indexName and queryVector array are required." });
    }
    const vector = getVector(mastra, vectorName);
    const results = await vector.query({ indexName, queryVector, topK, filter, includeVector });
    return results;
  } catch (error) {
    return handleError(error, "Error querying vectors");
  }
}
async function listIndexes({ mastra, vectorName }) {
  try {
    const vector = getVector(mastra, vectorName);
    const indexes = await vector.listIndexes();
    return indexes.filter(Boolean);
  } catch (error) {
    return handleError(error, "Error listing indexes");
  }
}
async function describeIndex({
  mastra,
  vectorName,
  indexName
}) {
  try {
    if (!indexName) {
      throw new HTTPException(400, { message: "Index name is required" });
    }
    const vector = getVector(mastra, vectorName);
    const stats = await vector.describeIndex({ indexName });
    return {
      dimension: stats.dimension,
      count: stats.count,
      metric: stats.metric?.toLowerCase()
    };
  } catch (error) {
    return handleError(error, "Error describing index");
  }
}
async function deleteIndex({
  mastra,
  vectorName,
  indexName
}) {
  try {
    if (!indexName) {
      throw new HTTPException(400, { message: "Index name is required" });
    }
    const vector = getVector(mastra, vectorName);
    await vector.deleteIndex({ indexName });
    return { success: true };
  } catch (error) {
    return handleError(error, "Error deleting index");
  }
}
async function listVectorStores({ mastra }) {
  try {
    const vectors = mastra.listVectors();
    if (!vectors) {
      return { vectors: [] };
    }
    const vectorList = Object.entries(vectors).map(([name, vector]) => ({
      name,
      id: vector.id || name,
      // Use the key as fallback when vector has no id property
      type: vector.constructor.name
      // Add any other metadata that might be useful
    }));
    return { vectors: vectorList };
  } catch (error) {
    return handleError(error, "Error listing vector stores");
  }
}
var UPSERT_VECTORS_ROUTE = createRoute({
  method: "POST",
  path: "/vector/:vectorName/upsert",
  responseType: "json",
  pathParamSchema: vectorNamePathParams,
  bodySchema: upsertVectorsBodySchema,
  responseSchema: upsertVectorsResponseSchema,
  summary: "Upsert vectors",
  description: "Inserts or updates vectors in the specified index",
  tags: ["Vectors"],
  requiresAuth: true,
  handler: async ({ mastra, vectorName, ...params }) => {
    try {
      const { indexName, vectors, metadata, ids } = params;
      if (!indexName || !vectors || !Array.isArray(vectors)) {
        throw new HTTPException(400, { message: "Invalid request index. indexName and vectors array are required." });
      }
      const vector = getVector(mastra, vectorName);
      const result = await vector.upsert({ indexName, vectors, metadata, ids });
      return { ids: result };
    } catch (error) {
      return handleError(error, "Error upserting vectors");
    }
  }
});
var CREATE_INDEX_ROUTE = createRoute({
  method: "POST",
  path: "/vector/:vectorName/create-index",
  responseType: "json",
  pathParamSchema: vectorNamePathParams,
  bodySchema: createIndexBodySchema,
  responseSchema: createIndexResponseSchema,
  summary: "Create index",
  description: "Creates a new vector index with the specified dimension and metric",
  tags: ["Vectors"],
  requiresAuth: true,
  handler: async ({ mastra, vectorName, ...params }) => {
    try {
      const { indexName, dimension, metric } = params;
      if (!indexName || typeof dimension !== "number" || dimension <= 0) {
        throw new HTTPException(400, {
          message: "Invalid request index, indexName and positive dimension number are required."
        });
      }
      if (metric && !["cosine", "euclidean", "dotproduct"].includes(metric)) {
        throw new HTTPException(400, { message: "Invalid metric. Must be one of: cosine, euclidean, dotproduct" });
      }
      const vector = getVector(mastra, vectorName);
      await vector.createIndex({ indexName, dimension, metric });
      return { success: true };
    } catch (error) {
      return handleError(error, "Error creating index");
    }
  }
});
var QUERY_VECTORS_ROUTE = createRoute({
  method: "POST",
  path: "/vector/:vectorName/query",
  responseType: "json",
  pathParamSchema: vectorNamePathParams,
  bodySchema: queryVectorsBodySchema,
  responseSchema: queryVectorsResponseSchema,
  summary: "Query vectors",
  description: "Performs a similarity search on the vector index",
  tags: ["Vectors"],
  requiresAuth: true,
  handler: async ({ mastra, vectorName, ...params }) => {
    try {
      const { indexName, queryVector, topK, filter, includeVector } = params;
      if (!indexName || !queryVector || !Array.isArray(queryVector)) {
        throw new HTTPException(400, {
          message: "Invalid request query. indexName and queryVector array are required."
        });
      }
      const vector = getVector(mastra, vectorName);
      const results = await vector.query({ indexName, queryVector, topK, filter, includeVector });
      return results;
    } catch (error) {
      return handleError(error, "Error querying vectors");
    }
  }
});
var LIST_INDEXES_ROUTE = createRoute({
  method: "GET",
  path: "/vector/:vectorName/indexes",
  responseType: "json",
  pathParamSchema: vectorNamePathParams,
  responseSchema: listIndexesResponseSchema,
  summary: "List indexes",
  description: "Returns a list of all indexes in the vector store",
  tags: ["Vectors"],
  requiresAuth: true,
  handler: async ({ mastra, vectorName }) => {
    try {
      const vector = getVector(mastra, vectorName);
      const indexes = await vector.listIndexes();
      return indexes.filter(Boolean);
    } catch (error) {
      return handleError(error, "Error listing indexes");
    }
  }
});
var DESCRIBE_INDEX_ROUTE = createRoute({
  method: "GET",
  path: "/vector/:vectorName/indexes/:indexName",
  responseType: "json",
  pathParamSchema: vectorIndexPathParams,
  responseSchema: describeIndexResponseSchema,
  summary: "Describe index",
  description: "Returns statistics and metadata for a specific index",
  tags: ["Vectors"],
  requiresAuth: true,
  handler: async ({ mastra, vectorName, indexName }) => {
    try {
      if (!indexName) {
        throw new HTTPException(400, { message: "Index name is required" });
      }
      const vector = getVector(mastra, vectorName);
      const stats = await vector.describeIndex({ indexName });
      return {
        dimension: stats.dimension,
        count: stats.count,
        metric: stats.metric?.toLowerCase()
      };
    } catch (error) {
      return handleError(error, "Error describing index");
    }
  }
});
var DELETE_INDEX_ROUTE = createRoute({
  method: "DELETE",
  path: "/vector/:vectorName/indexes/:indexName",
  responseType: "json",
  pathParamSchema: vectorIndexPathParams,
  responseSchema: deleteIndexResponseSchema,
  summary: "Delete index",
  description: "Deletes a vector index and all its data",
  tags: ["Vectors"],
  requiresAuth: true,
  handler: async ({ mastra, vectorName, indexName }) => {
    try {
      if (!indexName) {
        throw new HTTPException(400, { message: "Index name is required" });
      }
      const vector = getVector(mastra, vectorName);
      await vector.deleteIndex({ indexName });
      return { success: true };
    } catch (error) {
      return handleError(error, "Error deleting index");
    }
  }
});
var LIST_VECTORS_ROUTE = createRoute({
  method: "GET",
  path: "/vectors",
  responseType: "json",
  responseSchema: listVectorsResponseSchema,
  summary: "List vector stores",
  description: "Returns a list of all configured vector stores",
  tags: ["Vectors"],
  requiresAuth: true,
  handler: async ({ mastra }) => {
    try {
      const vectors = mastra.listVectors();
      if (!vectors) {
        return { vectors: [] };
      }
      const vectorList = Object.entries(vectors).map(([name, vector]) => ({
        id: vector.id || name,
        // Use the key as the ID since vectors might not have their own id property
        name,
        type: vector.constructor.name
      }));
      return { vectors: vectorList };
    } catch (error) {
      return handleError(error, "Error listing vector stores");
    }
  }
});
var LIST_EMBEDDERS_ROUTE = createRoute({
  method: "GET",
  path: "/embedders",
  responseType: "json",
  responseSchema: listEmbeddersResponseSchema,
  summary: "List available embedder models",
  description: "Returns a list of all available embedding models",
  tags: ["Vectors"],
  requiresAuth: true,
  handler: async () => {
    try {
      const embeddersList = EMBEDDING_MODELS.map((model) => ({
        id: `${model.provider}/${model.id}`,
        provider: model.provider,
        name: model.id,
        description: model.description || "",
        dimensions: model.dimensions,
        maxInputTokens: model.maxInputTokens
      }));
      return { embedders: embeddersList };
    } catch (error) {
      return handleError(error, "Error listing embedders");
    }
  }
});

export { CREATE_INDEX_ROUTE, DELETE_INDEX_ROUTE, DESCRIBE_INDEX_ROUTE, LIST_EMBEDDERS_ROUTE, LIST_INDEXES_ROUTE, LIST_VECTORS_ROUTE, QUERY_VECTORS_ROUTE, UPSERT_VECTORS_ROUTE, createIndex, deleteIndex, describeIndex, listIndexes, listVectorStores, queryVectors, upsertVectors, vector_exports };
//# sourceMappingURL=chunk-ANP3ESTF.js.map
//# sourceMappingURL=chunk-ANP3ESTF.js.map