import { readFileSync, existsSync, statSync, mkdirSync, writeFileSync } from 'node:fs';
import { dirname } from 'node:path';
import 'node:fs/promises';
import { normalizeProjectPath, getCcjkMemoryPath, getClaudeMemoryPath } from './memory-paths.mjs';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './constants.mjs';
import 'node:os';
import './index2.mjs';
import 'node:process';
import 'node:url';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import './fs-operations.mjs';
import 'node:crypto';

function parseAutoMemory(content) {
  const lines = content.split("\n");
  const entries = [];
  let currentEntry = null;
  for (const line of lines) {
    const headerMatch = line.match(/^(#{1,6})\s+(.+)$/);
    if (headerMatch) {
      if (currentEntry && currentEntry.content.length > 0) {
        entries.push(currentEntry);
      }
      currentEntry = {
        title: headerMatch[2].trim(),
        content: [],
        level: headerMatch[1].length
      };
    } else if (currentEntry && line.trim()) {
      currentEntry.content.push(line);
    }
  }
  if (currentEntry && currentEntry.content.length > 0) {
    entries.push(currentEntry);
  }
  return entries;
}
function autoMemoryToBrainContext(entries, projectPath) {
  const context = {
    facts: [],
    patterns: [],
    decisions: [],
    metadata: {
      source: "auto-memory",
      projectPath,
      syncedAt: (/* @__PURE__ */ new Date()).toISOString()
    }
  };
  for (const entry of entries) {
    const contentText = entry.content.join("\n").trim();
    const titleLower = entry.title.toLowerCase();
    if (titleLower.includes("architecture") || titleLower.includes("pattern") || titleLower.includes("design")) {
      context.patterns.push({
        name: entry.title,
        description: contentText,
        category: "architecture"
      });
    } else if (titleLower.includes("decision") || titleLower.includes("choice") || titleLower.includes("why")) {
      context.decisions.push({
        decision: entry.title,
        rationale: contentText,
        timestamp: (/* @__PURE__ */ new Date()).toISOString()
      });
    } else {
      context.facts.push({
        key: entry.title,
        value: contentText,
        confidence: 0.9
      });
    }
  }
  return context;
}

function readMemorySnapshot(path) {
  if (!existsSync(path)) {
    return {
      path,
      content: "",
      exists: false,
      hasContent: false,
      sizeBytes: 0,
      mtimeMs: 0
    };
  }
  const stats = statSync(path);
  const content = readFileSync(path, "utf-8");
  return {
    path,
    content,
    exists: true,
    hasContent: content.trim().length > 0,
    sizeBytes: stats.size,
    mtimeMs: stats.mtimeMs
  };
}
function writeMemorySnapshot(path, content) {
  mkdirSync(dirname(path), { recursive: true });
  writeFileSync(path, content, "utf-8");
}
function summarizeMemoryContent(content, projectPath) {
  if (!content.trim()) {
    return {
      parseMode: "empty",
      entryCount: 0,
      factCount: 0,
      patternCount: 0,
      decisionCount: 0
    };
  }
  const entries = parseAutoMemory(content);
  if (entries.length === 0) {
    return {
      parseMode: "freeform",
      entryCount: 0,
      factCount: 0,
      patternCount: 0,
      decisionCount: 0
    };
  }
  const context = autoMemoryToBrainContext(entries, projectPath || "global");
  return {
    parseMode: "structured",
    entryCount: entries.length,
    factCount: context.facts.length,
    patternCount: context.patterns.length,
    decisionCount: context.decisions.length
  };
}
function inspectSnapshots(claudeSnapshot, ccjkSnapshot, projectPath) {
  let source = "none";
  let sourceContent = "";
  let syncState = "empty";
  if (claudeSnapshot.hasContent || ccjkSnapshot.hasContent) {
    if (claudeSnapshot.hasContent && ccjkSnapshot.hasContent && claudeSnapshot.content === ccjkSnapshot.content) {
      source = "already-synced";
      sourceContent = claudeSnapshot.content;
      syncState = "in-sync";
    } else if (claudeSnapshot.hasContent && !ccjkSnapshot.hasContent) {
      source = "claude";
      sourceContent = claudeSnapshot.content;
      syncState = "claude-only";
    } else if (ccjkSnapshot.hasContent && !claudeSnapshot.hasContent) {
      source = "ccjk";
      sourceContent = ccjkSnapshot.content;
      syncState = "ccjk-only";
    } else if (claudeSnapshot.mtimeMs >= ccjkSnapshot.mtimeMs) {
      source = "claude";
      sourceContent = claudeSnapshot.content;
      syncState = "claude-newer";
    } else {
      source = "ccjk";
      sourceContent = ccjkSnapshot.content;
      syncState = "ccjk-newer";
    }
  }
  return {
    source,
    syncState,
    snapshots: {
      claude: {
        exists: claudeSnapshot.exists,
        hasContent: claudeSnapshot.hasContent,
        sizeBytes: claudeSnapshot.sizeBytes,
        mtimeMs: claudeSnapshot.mtimeMs
      },
      ccjk: {
        exists: ccjkSnapshot.exists,
        hasContent: ccjkSnapshot.hasContent,
        sizeBytes: ccjkSnapshot.sizeBytes,
        mtimeMs: ccjkSnapshot.mtimeMs
      }
    },
    ...summarizeMemoryContent(sourceContent, projectPath)
  };
}
function inspectMemoryFiles(options = {}) {
  const projectPath = options.projectPath ? normalizeProjectPath(options.projectPath) : void 0;
  const paths = {
    claude: getClaudeMemoryPath(projectPath, options.claudeDir),
    ccjk: getCcjkMemoryPath(projectPath, options.ccjkDir)
  };
  const claudeSnapshot = readMemorySnapshot(paths.claude);
  const ccjkSnapshot = readMemorySnapshot(paths.ccjk);
  return {
    scope: projectPath ? "project" : "global",
    paths,
    ...inspectSnapshots(claudeSnapshot, ccjkSnapshot, projectPath)
  };
}
function syncMemoryFiles(options = {}) {
  const inspection = inspectMemoryFiles(options);
  const updatedTargets = [];
  if (inspection.source === "claude" && inspection.syncState !== "in-sync") {
    writeMemorySnapshot(inspection.paths.ccjk, readFileSync(inspection.paths.claude, "utf-8"));
    updatedTargets.push("ccjk");
  } else if (inspection.source === "ccjk" && inspection.syncState !== "in-sync") {
    writeMemorySnapshot(inspection.paths.claude, readFileSync(inspection.paths.ccjk, "utf-8"));
    updatedTargets.push("claude");
  }
  return {
    ...inspection,
    updatedTargets
  };
}

export { inspectMemoryFiles, syncMemoryFiles };
