import { ChromaClient } from "chromadb";
import { v4 as uuidv4 } from "uuid";
class ChromaDBAdapter {
  client;
  collection = null;
  config;
  fallbackStorage = /* @__PURE__ */ new Map();
  constructor(config) {
    this.config = config;
    try {
      if (config.apiKey && (config.apiUrl?.includes("trychroma.com") || config.apiKey.startsWith("ck-"))) {
        const tenant = process.env.CHROMADB_TENANT;
        const database = process.env.CHROMADB_DATABASE || "stackmemory";
        this.client = new ChromaClient({
          ssl: true,
          host: "api.trychroma.com",
          port: 443,
          headers: {
            "X-Chroma-Token": config.apiKey
          },
          tenant,
          database
        });
      } else {
        this.client = new ChromaClient();
      }
    } catch (error) {
      console.log("Using in-memory ChromaDB client");
      this.client = new ChromaClient();
    }
  }
  async initialize() {
    try {
      const collectionName = this.config.collectionName || "stackmemory_context";
      this.collection = await this.client.getOrCreateCollection({
        name: collectionName,
        metadata: {
          description: "StackMemory Claude context",
          version: "2.0.0"
        }
      });
      console.log(
        `[${(/* @__PURE__ */ new Date()).toISOString()}] INFO: ChromaDB collection '${collectionName}' initialized`
      );
    } catch (error) {
      console.log(
        `ChromaDB service not available, using JSON fallback storage`
      );
      this.collection = null;
    }
  }
  async store(context) {
    const id = context.id || `ctx_${uuidv4()}`;
    const metadata = {
      timestamp: context.timestamp || (/* @__PURE__ */ new Date()).toISOString(),
      type: context.type || "context",
      user_id: context.user_id || this.config.userId || "default",
      project: context.project || "stackmemory"
    };
    if (context.session_id) metadata.session_id = context.session_id;
    if (context.metadata) {
      Object.entries(context.metadata).forEach(([key, value]) => {
        if (value !== void 0 && value !== null) {
          metadata[key] = value;
        }
      });
    }
    if (!this.collection) {
      await this.initialize();
    }
    try {
      if (this.collection) {
        await this.collection.upsert({
          ids: [id],
          documents: [context.content || JSON.stringify(context)],
          metadatas: [metadata]
        });
      } else {
        await this.storeToJsonFallback(id, context, metadata);
      }
      return {
        success: true,
        id,
        stored_at: (/* @__PURE__ */ new Date()).toISOString()
      };
    } catch (error) {
      console.error("Failed to store context:", error.message);
      try {
        await this.storeToJsonFallback(id, context, metadata);
        return { success: true, id, stored_at: (/* @__PURE__ */ new Date()).toISOString() };
      } catch (fallbackError) {
        return { success: false, error: fallbackError.message };
      }
    }
  }
  async storeToJsonFallback(id, context, metadata) {
    const fs = await import("fs");
    const path = await import("path");
    const os = await import("os");
    const storageDir = path.join(
      os.homedir(),
      ".stackmemory",
      "context-storage"
    );
    const storageFile = path.join(storageDir, "contexts.jsonl");
    if (!fs.existsSync(storageDir)) {
      fs.mkdirSync(storageDir, { recursive: true });
    }
    const entry = {
      id,
      content: context.content || JSON.stringify(context),
      metadata,
      stored_at: (/* @__PURE__ */ new Date()).toISOString()
    };
    fs.appendFileSync(storageFile, JSON.stringify(entry) + "\n");
  }
  async search(params) {
    if (!this.collection) {
      await this.initialize();
    }
    try {
      const query = params.query || "";
      const limit = params.limit || 10;
      const where = {};
      if (params.filter) {
        Object.entries(params.filter).forEach(([key, value]) => {
          if (value !== void 0 && value !== null) {
            where[key] = value;
          }
        });
      }
      const results = await this.collection.query({
        queryTexts: [query],
        nResults: limit,
        where: Object.keys(where).length > 0 ? where : void 0
      });
      const contexts = [];
      if (results.documents && results.documents[0]) {
        for (let i = 0; i < results.documents[0].length; i++) {
          contexts.push({
            id: results.ids[0][i],
            content: results.documents[0][i],
            metadata: results.metadatas?.[0]?.[i] || {},
            distance: results.distances?.[0]?.[i] || 0
          });
        }
      }
      return contexts;
    } catch (error) {
      console.error("Failed to search contexts:", error.message);
      return [];
    }
  }
  async deleteCollection() {
    if (this.collection) {
      await this.client.deleteCollection({
        name: this.config.collectionName || "stackmemory_context"
      });
      console.log("Collection deleted");
    }
  }
  async listCollections() {
    const collections = await this.client.listCollections();
    return collections;
  }
}
var chromadb_simple_default = ChromaDBAdapter;
export {
  ChromaDBAdapter,
  chromadb_simple_default as default
};
//# sourceMappingURL=chromadb-simple.js.map
