import { existsSync, readFileSync, mkdirSync, writeFileSync } from 'node:fs';
import a from './index5.mjs';
import { i as inquirer } from './index6.mjs';
import { x as K } from './main.mjs';
import { memoryCheck } from './memory-check.mjs';
import { getClaudeMemoryPath } from './memory-paths.mjs';
import { inspectMemoryFiles, syncMemoryFiles } from './memory-sync.mjs';
import { j as join } from '../shared/ccjk.bQ7Dh1g4.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:readline';
import 'stream';
import 'node:tty';
import 'node:process';
import 'node:async_hooks';
import '../shared/ccjk.Cjgrln_h.mjs';
import 'node:util';
import 'tty';
import 'fs';
import 'child_process';
import 'node:path';
import 'node:os';
import 'node:crypto';
import 'buffer';
import 'string_decoder';
import 'module';
import 'node:child_process';
import 'node:stream';
import 'constants';
import 'util';
import 'assert';
import 'path';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './constants.mjs';
import './index2.mjs';
import 'node:url';
import './fs-operations.mjs';
import 'node:fs/promises';

function formatTimestamp(timestampMs) {
  if (!timestampMs) {
    return "never";
  }
  return new Date(timestampMs).toISOString();
}
function formatSize(sizeBytes) {
  return `${(sizeBytes / 1024).toFixed(2)} KB`;
}
function describeSyncState(syncState) {
  switch (syncState) {
    case "in-sync":
      return "Claude and CCJK memory are in sync";
    case "claude-only":
      return "Only Claude memory has content";
    case "ccjk-only":
      return "Only CCJK memory has content";
    case "claude-newer":
      return "Claude memory is newer than the CCJK mirror";
    case "ccjk-newer":
      return "CCJK mirror is newer than Claude memory";
    case "empty":
      return "No memory content found";
  }
}
async function showMemoryStatus(projectPath) {
  const result = inspectMemoryFiles({ projectPath });
  console.log(a.cyan.bold("\n\u{1F4CA} Memory Status"));
  console.log(a.gray(`Scope:   ${result.scope}`));
  console.log(a.gray(`State:   ${describeSyncState(result.syncState)}`));
  console.log(a.gray(`Source:  ${result.source}`));
  console.log(a.gray(`Claude:  ${result.paths.claude}`));
  console.log(a.gray(`CCJK:    ${result.paths.ccjk}`));
  console.log("");
  console.log(a.bold("Claude Memory"));
  console.log(a.gray(`  Exists:   ${result.snapshots.claude.exists ? "yes" : "no"}`));
  console.log(a.gray(`  Content:  ${result.snapshots.claude.hasContent ? "yes" : "no"}`));
  console.log(a.gray(`  Size:     ${formatSize(result.snapshots.claude.sizeBytes)}`));
  console.log(a.gray(`  Updated:  ${formatTimestamp(result.snapshots.claude.mtimeMs)}`));
  console.log(a.bold("\nCCJK Mirror"));
  console.log(a.gray(`  Exists:   ${result.snapshots.ccjk.exists ? "yes" : "no"}`));
  console.log(a.gray(`  Content:  ${result.snapshots.ccjk.hasContent ? "yes" : "no"}`));
  console.log(a.gray(`  Size:     ${formatSize(result.snapshots.ccjk.sizeBytes)}`));
  console.log(a.gray(`  Updated:  ${formatTimestamp(result.snapshots.ccjk.mtimeMs)}`));
  if (result.parseMode === "structured") {
    console.log(a.bold("\nStructured Summary"));
    console.log(a.gray(`  Entries:    ${result.entryCount}`));
    console.log(a.gray(`  Facts:      ${result.factCount}`));
    console.log(a.gray(`  Patterns:   ${result.patternCount}`));
    console.log(a.gray(`  Decisions:  ${result.decisionCount}`));
  } else if (result.parseMode === "freeform") {
    console.log(a.bold("\nStructured Summary"));
    console.log(a.gray("  Freeform notes detected; no structured headings parsed"));
  }
  console.log("");
}
async function runMemoryDoctor(projectPath) {
  const result = inspectMemoryFiles({ projectPath });
  const health = await memoryCheck.check();
  console.log(a.cyan.bold("\n\u{1FA7A} Memory Doctor"));
  console.log(a.gray(`Project state: ${describeSyncState(result.syncState)}`));
  console.log(a.gray(`Health score:  ${health.score}/100 (${health.status})`));
  console.log(a.gray(`Summary:       ${health.message}`));
  if (health.details && health.details.length > 0) {
    console.log(a.bold("\nHealth Details"));
    for (const detail of health.details) {
      console.log(a.gray(`  ${detail}`));
    }
  }
  const recommendations = [];
  if (result.syncState === "claude-newer" || result.syncState === "ccjk-newer" || result.syncState === "claude-only" || result.syncState === "ccjk-only") {
    recommendations.push("Run `ccjk memory --sync` to reconcile Claude memory and the CCJK mirror");
  }
  if (result.syncState === "empty") {
    recommendations.push("Add project memory with `ccjk memory --edit` before relying on sync or doctor checks");
  }
  if (health.fix) {
    recommendations.push(health.fix);
  }
  if (recommendations.length > 0) {
    console.log(a.bold("\nRecommendations"));
    for (const recommendation of recommendations) {
      console.log(a.gray(`  - ${recommendation}`));
    }
  }
  if (health.command) {
    console.log(a.bold("\nSuggested Command"));
    console.log(a.gray(`  ${health.command}`));
  }
  console.log("");
}
function getMemoryPath(projectPath) {
  return getClaudeMemoryPath(projectPath);
}
function readMemory(memoryPath) {
  if (!existsSync(memoryPath)) {
    return "";
  }
  return readFileSync(memoryPath, "utf-8");
}
function writeMemory(memoryPath, content) {
  const dir = join(memoryPath, "..");
  if (!existsSync(dir)) {
    mkdirSync(dir, { recursive: true });
  }
  writeFileSync(memoryPath, content, "utf-8");
}
function displayMemory(content, title) {
  console.log(a.cyan.bold(`
${"=".repeat(60)}`));
  console.log(a.cyan.bold(`  ${title}`));
  console.log(a.cyan.bold(`${"=".repeat(60)}
`));
  if (!content.trim()) {
    console.log(a.gray("  (Empty memory)"));
  } else {
    const lines = content.split("\n");
    lines.forEach((line) => {
      if (line.startsWith("# ")) {
        console.log(a.yellow.bold(line));
      } else if (line.startsWith("## ")) {
        console.log(a.green.bold(line));
      } else if (line.startsWith("- ") || line.startsWith("* ")) {
        console.log(a.blue(line));
      } else if (line.startsWith("```")) {
        console.log(a.magenta(line));
      } else {
        console.log(line);
      }
    });
  }
  console.log(a.cyan.bold(`
${"=".repeat(60)}
`));
}
async function editMemoryInteractive(memoryPath) {
  const currentContent = readMemory(memoryPath);
  console.log(a.yellow("\nCurrent memory content:"));
  displayMemory(currentContent, "Current Memory");
  const { action } = await inquirer.prompt([
    {
      type: "list",
      name: "action",
      message: "What would you like to do?",
      choices: [
        { name: "Append new content", value: "append" },
        { name: "Replace entire content", value: "replace" },
        { name: "Clear memory", value: "clear" },
        { name: "Open in editor", value: "editor" },
        { name: "Cancel", value: "cancel" }
      ]
    }
  ]);
  if (action === "cancel") {
    console.log(a.gray("Cancelled."));
    return;
  }
  if (action === "clear") {
    const { confirmed } = await inquirer.prompt([
      {
        type: "confirm",
        name: "confirmed",
        message: "Are you sure you want to clear all memory?",
        default: false
      }
    ]);
    if (confirmed) {
      writeMemory(memoryPath, "");
      console.log(a.green("\u2713 Memory cleared"));
    }
    return;
  }
  if (action === "editor") {
    const editor = process.env.EDITOR || "vim";
    try {
      await K(editor, [memoryPath], { nodeOptions: { stdio: "inherit" } });
      console.log(a.green("\u2713 Memory updated"));
    } catch (error) {
      console.error(a.red("Failed to open editor:"), error);
    }
    return;
  }
  const { newContent } = await inquirer.prompt([
    {
      type: "input",
      name: "newContent",
      message: "Enter content (use \\n for line breaks):",
      default: ""
    }
  ]);
  if (!newContent.trim()) {
    console.log(a.gray("No content entered."));
    return;
  }
  const formattedContent = newContent.replace(/\\n/g, "\n");
  if (action === "append") {
    const updated = currentContent ? `${currentContent}

${formattedContent}` : formattedContent;
    writeMemory(memoryPath, updated);
    console.log(a.green("\u2713 Content appended to memory"));
  } else if (action === "replace") {
    writeMemory(memoryPath, formattedContent);
    console.log(a.green("\u2713 Memory replaced"));
  }
}
async function syncMemory(projectPath) {
  console.log(a.cyan("\nSyncing memory with AutoMemoryBridge..."));
  try {
    const result = syncMemoryFiles({ projectPath });
    if (result.source === "none") {
      console.log(a.yellow("\u26A0 No memory content found in Claude or CCJK storage"));
      console.log(a.gray(`  Claude: ${result.paths.claude}`));
      console.log(a.gray(`  CCJK:   ${result.paths.ccjk}`));
      return;
    }
    const sourceLabel = result.source === "already-synced" ? "Claude and CCJK memory" : `${result.source === "claude" ? "Claude" : "CCJK"} memory`;
    const targetLabel = result.updatedTargets.length === 0 ? "already in sync" : `updated ${result.updatedTargets.map((target) => target === "claude" ? "Claude" : "CCJK").join(", ")}`;
    console.log(a.green(`\u2713 Synced ${sourceLabel} (${targetLabel})`));
    console.log(a.gray(`  Claude: ${result.paths.claude}`));
    console.log(a.gray(`  CCJK:   ${result.paths.ccjk}`));
    if (result.parseMode === "structured") {
      console.log(a.gray(
        `  Structured entries: ${result.entryCount} (facts ${result.factCount}, patterns ${result.patternCount}, decisions ${result.decisionCount})`
      ));
    } else if (result.parseMode === "freeform") {
      console.log(a.gray("  Synced freeform notes (no structured headings detected)"));
    }
  } catch (error) {
    console.error(a.red("Failed to sync memory:"), error);
    throw error;
  }
}
async function memoryCommand(options) {
  const memoryPath = getMemoryPath(options.project);
  if (options.status) {
    await showMemoryStatus(options.project);
    return;
  }
  if (options.doctor) {
    await runMemoryDoctor(options.project);
    return;
  }
  if (options.view) {
    const content = readMemory(memoryPath);
    const title = options.project ? `Project Memory: ${options.project}` : "Global Memory";
    displayMemory(content, title);
    return;
  }
  if (options.edit) {
    await editMemoryInteractive(memoryPath);
    return;
  }
  if (options.sync) {
    await syncMemory(options.project);
    return;
  }
  console.log(a.cyan.bold("\n\u{1F4DD} Memory Management"));
  console.log(a.gray(`Memory path: ${memoryPath}
`));
  const { action } = await inquirer.prompt([
    {
      type: "list",
      name: "action",
      message: "What would you like to do?",
      choices: [
        { name: "\u{1F4CA} Status", value: "status" },
        { name: "\u{1FA7A} Doctor", value: "doctor" },
        { name: "\u{1F441}\uFE0F  View memory", value: "view" },
        { name: "\u270F\uFE0F  Edit memory", value: "edit" },
        { name: "\u{1F504} Sync memory (AutoMemoryBridge)", value: "sync" },
        { name: "\u{1F4CA} Memory stats", value: "stats" },
        { name: "\u{1F6AA} Exit", value: "exit" }
      ]
    }
  ]);
  switch (action) {
    case "status":
      await showMemoryStatus(options.project);
      break;
    case "doctor":
      await runMemoryDoctor(options.project);
      break;
    case "view": {
      const content = readMemory(memoryPath);
      const title = options.project ? `Project Memory: ${options.project}` : "Global Memory";
      displayMemory(content, title);
      break;
    }
    case "edit":
      await editMemoryInteractive(memoryPath);
      break;
    case "sync":
      await syncMemory(options.project);
      break;
    case "stats": {
      const content = readMemory(memoryPath);
      const lines = content.split("\n").length;
      const words = content.split(/\s+/).filter((w) => w.length > 0).length;
      const chars = content.length;
      console.log(a.cyan("\n\u{1F4CA} Memory Statistics:"));
      console.log(a.gray(`  Lines: ${lines}`));
      console.log(a.gray(`  Words: ${words}`));
      console.log(a.gray(`  Characters: ${chars}`));
      console.log(a.gray(`  Size: ${(chars / 1024).toFixed(2)} KB
`));
      break;
    }
    case "exit":
      console.log(a.gray("Goodbye!"));
      break;
  }
}

export { memoryCommand };
