#!/usr/bin/env node
import { Command } from "commander";
import { readFileSync } from "fs";
import { join, dirname } from "path";
import { fileURLToPath } from "url";
import Database from "better-sqlite3";
import { FrameManager } from "../core/context/frame-manager.js";
import { SessionManager } from "../core/session/session-manager.js";
import { pluginManager, loadPlugins } from "../plugins/loader.js";
import { logger } from "../core/monitoring/logger.js";
const __dirname = dirname(fileURLToPath(import.meta.url));
const packageJson = JSON.parse(
  readFileSync(join(__dirname, "../../package.json"), "utf-8")
);
const program = new Command();
program.name("stackmemory").description("Git for AI context - persistent memory across sessions").version(packageJson.version);
program.command("init").description("Initialize StackMemory in current directory").action(async () => {
  const sessionManager = SessionManager.getInstance();
  await sessionManager.initialize();
  const session = await sessionManager.getOrCreateSession();
  console.log("\u2705 StackMemory initialized");
  console.log(`   Project: ${session.projectId}`);
  console.log(`   Session: ${session.sessionId.slice(0, 8)}`);
});
program.command("status").description("Show current context status").action(async () => {
  const sessionManager = SessionManager.getInstance();
  await sessionManager.initialize();
  const session = await sessionManager.getOrCreateSession();
  const dbPath = join(process.cwd(), ".stackmemory", "context.db");
  const db = new Database(dbPath);
  const frameManager = new FrameManager(db, session.projectId);
  const activeFrames = frameManager.getActiveFramePath();
  const depth = frameManager.getStackDepth();
  console.log("\u{1F4CA} StackMemory Status:");
  console.log(`   Session: ${session.sessionId.slice(0, 8)}`);
  console.log(`   Stack depth: ${depth}`);
  console.log(`   Active frames: ${activeFrames.length}`);
  if (activeFrames.length > 0) {
    console.log("\n   Current stack:");
    activeFrames.slice(0, 5).forEach((frame, i) => {
      console.log(`     ${i + 1}. ${frame.name} [${frame.type}]`);
    });
  }
});
program.command("save [message]").description("Save current context with optional message").action(async (message) => {
  const sessionManager = SessionManager.getInstance();
  await sessionManager.initialize();
  const session = await sessionManager.getOrCreateSession();
  const dbPath = join(process.cwd(), ".stackmemory", "context.db");
  const db = new Database(dbPath);
  const frameManager = new FrameManager(db, session.projectId);
  const frame = await frameManager.createFrame({
    type: "context",
    name: message || "Manual save",
    content: message || "",
    metadata: {
      savedAt: (/* @__PURE__ */ new Date()).toISOString(),
      manual: true
    }
  });
  console.log("\u2705 Context saved");
  console.log(`   Frame ID: ${frame.frame_id.slice(0, 8)}`);
});
program.command("load [query]").description("Load context by search query").argument("[query]", "Search query for context").action(async (query) => {
  const sessionManager = SessionManager.getInstance();
  await sessionManager.initialize();
  const dbPath = join(process.cwd(), ".stackmemory", "context.db");
  const db = new Database(dbPath);
  let whereClause = "";
  const params = [];
  if (query) {
    whereClause = "WHERE name LIKE ? OR content LIKE ?";
    params.push(`%${query}%`, `%${query}%`);
  }
  const frames = db.prepare(
    `
      SELECT frame_id, name, type, datetime(created_at, 'unixepoch') as created
      FROM frames
      ${whereClause}
      ORDER BY created_at DESC
      LIMIT 10
    `
  ).all(...params);
  if (frames.length === 0) {
    console.log("No matching context found");
    return;
  }
  console.log("\u{1F4DA} Found contexts:");
  frames.forEach((f, i) => {
    console.log(`   ${i + 1}. ${f.name} [${f.type}] - ${f.created}`);
  });
});
program.command("sync").description("Sync context with remote storage").option("--push", "Push local changes to remote").option("--pull", "Pull remote changes to local").action(async (options) => {
  console.log("\u{1F504} Sync functionality:");
  if (options.push) {
    console.log("   Pushing to remote storage...");
  } else if (options.pull) {
    console.log("   Pulling from remote storage...");
  } else {
    console.log("   Use --push or --pull to specify direction");
  }
});
program.command("plugin <action> [name]").description("Manage plugins (list/enable/disable)").action(async (action, name) => {
  if (action === "list") {
    await loadPlugins();
    const plugins = pluginManager.getAllPlugins();
    console.log("\u{1F4E6} Available plugins:");
    if (plugins.length === 0) {
      console.log("   No plugins loaded");
      console.log(
        "   Set ENABLE_LINEAR_PLUGIN=true to enable Linear integration"
      );
    } else {
      plugins.forEach((p) => {
        console.log(`   - ${p.name} v${p.version}: ${p.description}`);
      });
    }
  } else if (action === "enable" && name) {
    console.log(`Enabling plugin: ${name}`);
  } else if (action === "disable" && name) {
    console.log(`Disabling plugin: ${name}`);
  } else {
    console.log("Usage: stackmemory plugin <list|enable|disable> [name]");
  }
});
loadPlugins().then(() => {
  const pluginCommands = pluginManager.getAllCommands();
  for (const cmd of pluginCommands) {
    const command = program.command(cmd.name).description(cmd.description).action(cmd.action);
    if (cmd.options) {
      for (const opt of cmd.options) {
        command.option(opt.flag, opt.description, opt.defaultValue);
      }
    }
  }
  program.parse(process.argv);
}).catch((error) => {
  logger.error("Failed to load plugins", error);
  program.parse(process.argv);
});
if (!process.argv.slice(2).length) {
  program.outputHelp();
}
//# sourceMappingURL=streamlined-cli.js.map
