const fs = require("fs");
const path = require("path");
const { loadProvidersConfig, DEFAULT_PATHS, search } = require("../lib/providers/local-memory-adapter");
const { loadProvidersConfig: loadGraphCfg, DEFAULT_PATHS: GRAPH_PATHS, query } = require("../lib/providers/local-graph-adapter");
const { localContextEnabled } = require("../lib/context-memory-bridge");

function fileStatus(rootDir, rel) {
  const abs = path.join(rootDir, rel);
  return { path: rel, exists: fs.existsSync(abs) };
}

module.exports = async function memory(args, flags) {
  const sub = args[0];
  const rootDir = process.cwd();

  if (sub !== "status") {
    console.error("Usage: capint memory status [--json]");
    process.exit(1);
  }

  const memCfg = loadProvidersConfig(rootDir);
  const graphCfg = loadGraphCfg(rootDir);
  const memPaths = memCfg?.memory?.paths || DEFAULT_PATHS;
  const graphPaths = graphCfg?.graph?.paths || GRAPH_PATHS;

  const report = {
    mode: "read_only",
    local_context_flag: localContextEnabled({}),
    env_CAPINT_LOCAL_CONTEXT: process.env.CAPINT_LOCAL_CONTEXT || null,
    providers_config: fs.existsSync(path.join(rootDir, ".capint", "providers.json")),
    memory: {
      driver: memCfg?.memory?.driver || "local (default)",
      paths: memPaths.map((p) => fileStatus(rootDir, p))
    },
    graph: {
      driver: graphCfg?.graph?.driver || "local (default)",
      paths: graphPaths.map((p) => fileStatus(rootDir, p))
    },
    sample_memory_search: search(rootDir, "", { config: memCfg }).hits.length,
    sample_graph_query: query(rootDir, null, { config: graphCfg }).excerpts.length
  };

  if (flags.json) {
    console.log(JSON.stringify(report, null, 2));
    return;
  }

  console.log("\n## CapInt memory status\n");
  console.log(`Local context hot-path: ${report.local_context_flag ? "enabled" : "off (set CAPINT_LOCAL_CONTEXT=1)"}`);
  console.log(`providers.json: ${report.providers_config ? "yes" : "no (optional)"}\n`);
  console.log("Memory paths:");
  for (const p of report.memory.paths) {
    console.log(`  ${p.exists ? "✓" : "✗"} ${p.path}`);
  }
  console.log("\nGraph paths:");
  for (const p of report.graph.paths) {
    console.log(`  ${p.exists ? "✓" : "✗"} ${p.path}`);
  }
  console.log("");
};
