import { mkdir, writeFile, access, readFile, readdir, stat } from 'node:fs/promises';
import { d as dirname, j as join, r as relative } from '../shared/ccjk.bQ7Dh1g4.mjs';
import { constants, existsSync, lstatSync, readFileSync, readdirSync } from 'node:fs';
import a from './index5.mjs';
import { getTranslation } from './index2.mjs';
import { inspectMemoryFiles } from './memory-sync.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:process';
import 'node:url';
import 'node:path';
import './memory-paths.mjs';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './constants.mjs';
import 'node:os';
import './fs-operations.mjs';
import 'node:crypto';

function buildContextPack(intelligence, options = {}) {
  const {
    projectName = "Unknown Project",
    projectDescription = "No description provided",
    includeCommands = true,
    includeRepoMap = true
  } = options;
  return {
    projectIdentity: buildProjectIdentity(projectName, projectDescription, intelligence.stack),
    stack: intelligence.stack,
    commands: includeCommands ? intelligence.commands : [],
    repoTopology: includeRepoMap ? buildRepoTopology(intelligence.repoMap) : "",
    testPolicy: buildTestPolicy(intelligence.commands),
    riskZones: identifyRiskZones(intelligence.repoMap),
    retrievalInstructions: buildRetrievalInstructions(intelligence.stack),
    generatedAt: (/* @__PURE__ */ new Date()).toISOString()
  };
}
function buildProjectIdentity(name, description, stack) {
  const parts = [
    `Project: ${name}`,
    `Description: ${description}`,
    ""
  ];
  if (stack.languages.length > 0) {
    parts.push(`Languages: ${stack.languages.join(", ")}`);
  }
  if (stack.frameworks.length > 0) {
    const frameworkList = stack.frameworks.map((f) => `${f.name}${f.version ? ` ${f.version}` : ""}`).join(", ");
    parts.push(`Frameworks: ${frameworkList}`);
  }
  if (stack.packageManager) {
    parts.push(`Package Manager: ${stack.packageManager}`);
  }
  if (stack.runtime) {
    parts.push(`Runtime: ${stack.runtime}`);
  }
  return parts.join("\n");
}
function buildRepoTopology(repoMap) {
  const parts = ["Repository Structure:", ""];
  const byType = /* @__PURE__ */ new Map();
  for (const dir of repoMap.directories) {
    const dirs = byType.get(dir.type) || [];
    dirs.push(dir);
    byType.set(dir.type, dirs);
  }
  const typeOrder = [
    "source",
    "test",
    "config",
    "docs",
    "assets",
    "other"
  ];
  for (const type of typeOrder) {
    const dirs = byType.get(type);
    if (dirs && dirs.length > 0) {
      parts.push(`${type.toUpperCase()}:`);
      for (const dir of dirs.slice(0, 5)) {
        parts.push(`  - ${dir.relativePath} (${dir.fileCount} files)`);
      }
      parts.push("");
    }
  }
  parts.push(`Total: ${repoMap.totalFiles} files`);
  return parts.join("\n");
}
function buildTestPolicy(commands) {
  const testCommands = commands.filter((c) => c.type === "test");
  if (testCommands.length === 0) {
    return "No test commands detected. Consider adding tests before making changes.";
  }
  const parts = [
    "Test Policy:",
    "",
    "Available test commands:"
  ];
  for (const cmd of testCommands) {
    parts.push(`  - ${cmd.name}: ${cmd.command}`);
  }
  parts.push("");
  parts.push("Always run tests before committing changes.");
  return parts.join("\n");
}
function identifyRiskZones(repoMap) {
  const riskZones = [];
  const buildDirs = repoMap.directories.filter((d) => d.type === "build");
  for (const dir of buildDirs) {
    riskZones.push(`${dir.relativePath} (generated files)`);
  }
  const largeDirs = repoMap.directories.filter((d) => d.fileCount > 100).sort((a, b) => b.fileCount - a.fileCount).slice(0, 3);
  for (const dir of largeDirs) {
    riskZones.push(`${dir.relativePath} (${dir.fileCount} files - high complexity)`);
  }
  return riskZones;
}
function buildRetrievalInstructions(stack) {
  const parts = [
    "Retrieval-First Instructions:",
    ""
  ];
  if (stack.frameworks.length > 0) {
    parts.push("For framework-specific questions:");
    for (const framework of stack.frameworks) {
      parts.push(`  - ${framework.name}: Check local docs or official documentation for version ${framework.version || "latest"}`);
    }
    parts.push("");
  }
  parts.push("For repository conventions:");
  parts.push("  - Check existing code patterns before implementing new features");
  parts.push("  - Review test files to understand testing conventions");
  parts.push("  - Consult configuration files for build and deployment settings");
  return parts.join("\n");
}

async function writeClaudeContext(contextPack, outputPath) {
  const content = formatClaudeContext(contextPack);
  await mkdir(dirname(outputPath), { recursive: true });
  await writeFile(outputPath, content, "utf-8");
}
function formatClaudeContext(pack) {
  const sections = [];
  sections.push("# CLAUDE.md");
  sections.push("");
  sections.push("This file provides guidance to Claude Code when working with code in this repository.");
  sections.push("");
  sections.push(`Generated: ${new Date(pack.generatedAt).toLocaleString()}`);
  sections.push("");
  sections.push("---");
  sections.push("");
  sections.push("## Project Information");
  sections.push("");
  sections.push(pack.projectIdentity);
  sections.push("");
  if (pack.stack.frameworks.length > 0) {
    sections.push("## Technology Stack");
    sections.push("");
    for (const framework of pack.stack.frameworks) {
      sections.push(`### ${framework.name}`);
      if (framework.version) {
        sections.push(`Version: ${framework.version}`);
      }
      sections.push(`Type: ${framework.type}`);
      sections.push("");
    }
  }
  if (pack.commands.length > 0) {
    sections.push("## Available Commands");
    sections.push("");
    const commandsByType = /* @__PURE__ */ new Map();
    for (const cmd of pack.commands) {
      const cmds = commandsByType.get(cmd.type) || [];
      cmds.push(cmd);
      commandsByType.set(cmd.type, cmds);
    }
    for (const [type, commands] of commandsByType) {
      sections.push(`### ${type.charAt(0).toUpperCase() + type.slice(1)}`);
      sections.push("");
      for (const cmd of commands) {
        sections.push(`- \`${cmd.name}\`: ${cmd.command}`);
        if (cmd.description) {
          sections.push(`  ${cmd.description}`);
        }
      }
      sections.push("");
    }
  }
  if (pack.repoTopology) {
    sections.push("## Repository Structure");
    sections.push("");
    sections.push(pack.repoTopology);
    sections.push("");
  }
  if (pack.testPolicy) {
    sections.push("## Testing");
    sections.push("");
    sections.push(pack.testPolicy);
    sections.push("");
  }
  if (pack.riskZones.length > 0) {
    sections.push("## Risk Zones");
    sections.push("");
    sections.push("Be cautious when modifying these areas:");
    sections.push("");
    for (const zone of pack.riskZones) {
      sections.push(`- ${zone}`);
    }
    sections.push("");
  }
  if (pack.retrievalInstructions) {
    sections.push("## Development Guidelines");
    sections.push("");
    sections.push(pack.retrievalInstructions);
    sections.push("");
  }
  return sections.join("\n");
}

async function detectCommands(projectRoot = ".") {
  const commands = [];
  const packageJsonPath = join(projectRoot, "package.json");
  if (await fileExists$1(packageJsonPath)) {
    commands.push(...await detectNpmScripts(packageJsonPath));
  }
  const makefilePath = join(projectRoot, "Makefile");
  if (await fileExists$1(makefilePath)) {
    commands.push(...await detectMakeTargets(makefilePath));
  }
  const pyprojectPath = join(projectRoot, "pyproject.toml");
  if (await fileExists$1(pyprojectPath)) {
    commands.push(...await detectPoetryScripts(pyprojectPath));
  }
  return commands;
}
async function detectNpmScripts(packageJsonPath) {
  const commands = [];
  try {
    const content = await readFile(packageJsonPath, "utf-8");
    const packageJson = JSON.parse(content);
    if (packageJson.scripts) {
      for (const [name, command] of Object.entries(packageJson.scripts)) {
        commands.push({
          name,
          command,
          type: inferCommandType(name)
        });
      }
    }
  } catch {
  }
  return commands;
}
async function detectMakeTargets(makefilePath) {
  const commands = [];
  try {
    const content = await readFile(makefilePath, "utf-8");
    const lines = content.split("\n");
    for (const line of lines) {
      const match = line.match(/^([\w-]+):\s*(.*)/);
      if (match) {
        const [, name, deps] = match;
        if (!name.startsWith(".") && name !== "PHONY") {
          commands.push({
            name,
            command: `make ${name}`,
            type: inferCommandType(name),
            description: deps || void 0
          });
        }
      }
    }
  } catch {
  }
  return commands;
}
async function detectPoetryScripts(pyprojectPath) {
  const commands = [];
  try {
    const content = await readFile(pyprojectPath, "utf-8");
    const scriptsMatch = content.match(/\[tool\.poetry\.scripts\]([\s\S]*?)(?:\[|$)/);
    if (scriptsMatch) {
      const scriptsSection = scriptsMatch[1];
      const lines = scriptsSection.split("\n");
      for (const line of lines) {
        const match = line.match(/^([\w-]+)\s*=\s*"([^"]+)"/);
        if (match) {
          const [, name, command] = match;
          commands.push({
            name,
            command,
            type: inferCommandType(name)
          });
        }
      }
    }
  } catch {
  }
  return commands;
}
function inferCommandType(name) {
  const lowerName = name.toLowerCase();
  if (lowerName.includes("build") || lowerName.includes("compile")) {
    return "build";
  }
  if (lowerName.includes("test") || lowerName.includes("spec")) {
    return "test";
  }
  if (lowerName.includes("lint") || lowerName.includes("format")) {
    return "lint";
  }
  if (lowerName.includes("dev") || lowerName.includes("watch")) {
    return "dev";
  }
  if (lowerName.includes("start") || lowerName.includes("serve")) {
    return "start";
  }
  if (lowerName.includes("deploy") || lowerName.includes("publish")) {
    return "deploy";
  }
  return "other";
}
async function fileExists$1(path) {
  try {
    await access(path, constants.F_OK);
    return true;
  } catch {
    return false;
  }
}

async function mapRepository(projectRoot = ".", options = {}) {
  const { maxDepth = 3, ignorePatterns = getDefaultIgnorePatterns() } = options;
  const directories = [];
  let totalFiles = 0;
  let totalSize = 0;
  await scanDirectory(projectRoot, projectRoot, 0, maxDepth, ignorePatterns, directories);
  for (const dir of directories) {
    totalFiles += dir.fileCount;
    totalSize += dir.size;
  }
  return {
    root: projectRoot,
    directories,
    totalFiles,
    totalSize
  };
}
async function scanDirectory(root, dir, depth, maxDepth, ignorePatterns, result) {
  if (depth > maxDepth) {
    return;
  }
  try {
    const entries = await readdir(dir, { withFileTypes: true });
    let fileCount = 0;
    let size = 0;
    for (const entry of entries) {
      const fullPath = join(dir, entry.name);
      const relativePath = relative(root, fullPath);
      if (shouldIgnore(relativePath, ignorePatterns)) {
        continue;
      }
      if (entry.isDirectory()) {
        await scanDirectory(root, fullPath, depth + 1, maxDepth, ignorePatterns, result);
      } else if (entry.isFile()) {
        fileCount++;
        try {
          const stats = await stat(fullPath);
          size += stats.size;
        } catch {
        }
      }
    }
    if (fileCount > 0 || depth === 0) {
      result.push({
        path: dir,
        relativePath: relative(root, dir) || ".",
        type: inferDirectoryType(relative(root, dir)),
        fileCount,
        size
      });
    }
  } catch {
  }
}
function shouldIgnore(path, patterns) {
  for (const pattern of patterns) {
    if (path.includes(pattern)) {
      return true;
    }
  }
  return false;
}
function getDefaultIgnorePatterns() {
  return [
    "node_modules",
    ".git",
    "dist",
    "build",
    "out",
    ".next",
    ".nuxt",
    "coverage",
    ".cache",
    ".turbo",
    "__pycache__",
    ".pytest_cache",
    "venv",
    ".venv",
    "target",
    "vendor"
  ];
}
function inferDirectoryType(path) {
  const lowerPath = path.toLowerCase();
  if (lowerPath.match(/^(src|lib|app|packages|components|pages|views)/)) {
    return "source";
  }
  if (lowerPath.match(/^(test|tests|__tests__|spec|specs|e2e)/)) {
    return "test";
  }
  if (lowerPath.match(/^(config|configs|\.config|\.github|\.vscode)/)) {
    return "config";
  }
  if (lowerPath.match(/^(docs|documentation|wiki)/)) {
    return "docs";
  }
  if (lowerPath.match(/^(dist|build|out|\.next|\.nuxt|target)/)) {
    return "build";
  }
  if (lowerPath.match(/^(public|static|assets|images|media)/)) {
    return "assets";
  }
  return "other";
}

async function detectStack(projectRoot = ".") {
  const languages = await detectLanguages(projectRoot);
  const frameworks = await detectFrameworks(projectRoot);
  const packageManager = await detectPackageManager(projectRoot);
  const runtime = await detectRuntime(projectRoot);
  return {
    languages,
    frameworks,
    packageManager,
    runtime
  };
}
async function detectLanguages(projectRoot) {
  const languages = /* @__PURE__ */ new Set();
  if (await fileExists(join(projectRoot, "tsconfig.json"))) {
    languages.add("TypeScript");
  }
  if (await fileExists(join(projectRoot, "package.json"))) {
    languages.add("JavaScript");
  }
  if (await fileExists(join(projectRoot, "requirements.txt")) || await fileExists(join(projectRoot, "pyproject.toml")) || await fileExists(join(projectRoot, "setup.py"))) {
    languages.add("Python");
  }
  if (await fileExists(join(projectRoot, "go.mod"))) {
    languages.add("Go");
  }
  if (await fileExists(join(projectRoot, "Cargo.toml"))) {
    languages.add("Rust");
  }
  if (await fileExists(join(projectRoot, "pom.xml")) || await fileExists(join(projectRoot, "build.gradle"))) {
    languages.add("Java");
  }
  return Array.from(languages);
}
async function detectFrameworks(projectRoot) {
  const frameworks = [];
  const packageJsonPath = join(projectRoot, "package.json");
  if (await fileExists(packageJsonPath)) {
    const packageJson = await readPackageJson(packageJsonPath);
    if (packageJson) {
      frameworks.push(...detectNodeFrameworks(packageJson));
    }
  }
  const requirementsPath = join(projectRoot, "requirements.txt");
  if (await fileExists(requirementsPath)) {
    frameworks.push(...await detectPythonFrameworks(requirementsPath));
  }
  return frameworks;
}
function detectNodeFrameworks(packageJson) {
  const frameworks = [];
  const deps = { ...packageJson.dependencies, ...packageJson.devDependencies };
  const frameworkMap = {
    next: { type: "fullstack" },
    react: { type: "frontend" },
    vue: { type: "frontend" },
    nuxt: { type: "fullstack" },
    svelte: { type: "frontend" },
    angular: { type: "frontend" },
    express: { type: "backend" },
    fastify: { type: "backend" },
    koa: { type: "backend" },
    nestjs: { type: "backend" },
    vitest: { type: "testing" },
    jest: { type: "testing" },
    vite: { type: "build" },
    webpack: { type: "build" },
    esbuild: { type: "build" }
  };
  for (const [name, config] of Object.entries(frameworkMap)) {
    if (deps[name]) {
      frameworks.push({
        name,
        version: deps[name].replace(/^[\^~]/, ""),
        type: config.type
      });
    }
  }
  return frameworks;
}
async function detectPythonFrameworks(requirementsPath) {
  const frameworks = [];
  try {
    const content = await readFile(requirementsPath, "utf-8");
    const lines = content.split("\n");
    const frameworkMap = {
      django: { type: "fullstack" },
      flask: { type: "backend" },
      fastapi: { type: "backend" },
      pytest: { type: "testing" }
    };
    for (const line of lines) {
      const match = line.match(/^([\w-]+)(?:==|>=|<=)?([\d.]+)?/);
      if (match) {
        const [, name, version] = match;
        const config = frameworkMap[name.toLowerCase()];
        if (config) {
          frameworks.push({
            name,
            version: version || null,
            type: config.type
          });
        }
      }
    }
  } catch {
  }
  return frameworks;
}
async function detectPackageManager(projectRoot) {
  if (await fileExists(join(projectRoot, "pnpm-lock.yaml"))) {
    return "pnpm";
  }
  if (await fileExists(join(projectRoot, "yarn.lock"))) {
    return "yarn";
  }
  if (await fileExists(join(projectRoot, "package-lock.json"))) {
    return "npm";
  }
  if (await fileExists(join(projectRoot, "bun.lockb"))) {
    return "bun";
  }
  return null;
}
async function detectRuntime(projectRoot) {
  const packageJsonPath = join(projectRoot, "package.json");
  if (await fileExists(packageJsonPath)) {
    const packageJson = await readPackageJson(packageJsonPath);
    if (packageJson?.engines?.node) {
      return `Node.js ${packageJson.engines.node}`;
    }
    return "Node.js";
  }
  if (await fileExists(join(projectRoot, "go.mod"))) {
    return "Go";
  }
  if (await fileExists(join(projectRoot, "Cargo.toml"))) {
    return "Rust";
  }
  return null;
}
async function readPackageJson(path) {
  try {
    const content = await readFile(path, "utf-8");
    return JSON.parse(content);
  } catch {
    return null;
  }
}
async function fileExists(path) {
  try {
    await access(path, constants.F_OK);
    return true;
  } catch {
    return false;
  }
}

async function analyzeProject(projectRoot = ".") {
  const [stack, commands, repoMap] = await Promise.all([
    detectStack(projectRoot),
    detectCommands(projectRoot),
    mapRepository(projectRoot)
  ]);
  return {
    stack,
    commands,
    repoMap,
    timestamp: (/* @__PURE__ */ new Date()).toISOString()
  };
}

async function analyzeContext() {
  const t = getTranslation();
  console.log(a.green.bold(`
\u{1F50D} ${t("context.analyzing")}
`));
  const analysis = analyzeDirectory(process.cwd());
  console.log(a.white(`${t("context.filesInContext")}: ${a.bold(analysis.files.length.toString())}`));
  console.log(a.white(`${t("context.estimatedTokens")}: ${a.bold(analysis.totalTokens.toLocaleString())}`));
  console.log(a.white(`${t("context.totalSize")}: ${a.bold(formatBytes(analysis.totalSize))}
`));
  if (analysis.largestFiles.length > 0) {
    console.log(a.yellow(`${t("context.largestFiles")}:
`));
    for (const file of analysis.largestFiles.slice(0, 5)) {
      const sizeStr = formatBytes(file.size);
      const tokensStr = file.tokens.toLocaleString();
      console.log(`  ${a.white(file.path)}`);
      console.log(`    ${a.dim(`${t("context.size")}: ${sizeStr} | ${t("context.tokens")}: ${tokensStr}`)}`);
    }
    console.log();
  }
}
async function showContextStatus() {
  const t = getTranslation();
  const memoryStatus = inspectMemoryFiles({ projectPath: process.cwd() });
  console.log(a.green.bold(`
\u{1F4CA} ${t("context.status")}
`));
  console.log(a.white(`Project: ${a.bold(process.cwd())}`));
  const claudeMdPath = join(process.cwd(), "CLAUDE.md");
  const hasClaudeMd = existsSync(claudeMdPath);
  console.log(`${hasClaudeMd ? a.green("\u2713") : a.red("\u2717")} CLAUDE.md`);
  if (hasClaudeMd) {
    const stats = lstatSync(claudeMdPath);
    const content = readFileSync(claudeMdPath, "utf-8");
    const tokens = estimateTokens(content);
    console.log(`  ${a.dim(`${t("context.size")}: ${formatBytes(stats.size)} | ${t("context.tokens")}: ${tokens.toLocaleString()}`)}`);
  }
  console.log();
  const claudeIgnorePath = join(process.cwd(), ".claudeignore");
  const hasIgnore = existsSync(claudeIgnorePath);
  console.log(`${hasIgnore ? a.green("\u2713") : a.yellow("\u25CB")} .claudeignore`);
  const contextFiles = findContextFiles(process.cwd());
  console.log(`
${a.white(`${t("context.additionalFiles")}: ${contextFiles.length}`)}
`);
  for (const file of contextFiles.slice(0, 10)) {
    const tokens = estimateTokens(readFileSync(file, "utf-8"));
    lstatSync(file).size;
    console.log(`  ${a.white(file)} ${a.dim(`(${tokens.toLocaleString()} ${t("context.tokens")})`)}`);
  }
  if (contextFiles.length > 10) {
    console.log(`  ${a.dim(`... and ${contextFiles.length - 10} more`)}`);
  }
  console.log(a.yellow("\nMemory\n"));
  console.log(`  ${a.white(`State: ${describeMemorySyncState(memoryStatus.syncState)}`)}`);
  console.log(`  ${a.dim(`Claude: ${memoryStatus.paths.claude}`)}`);
  console.log(`  ${a.dim(`CCJK:   ${memoryStatus.paths.ccjk}`)}`);
  if (memoryStatus.parseMode === "structured") {
    console.log(`  ${a.dim(`Entries: ${memoryStatus.entryCount} | Facts: ${memoryStatus.factCount} | Patterns: ${memoryStatus.patternCount} | Decisions: ${memoryStatus.decisionCount}`)}`);
  } else if (memoryStatus.parseMode === "freeform") {
    console.log(`  ${a.dim("Structured parsing: freeform notes detected")}`);
  } else {
    console.log(`  ${a.dim("Structured parsing: no memory content found")}`);
  }
  console.log(a.yellow("\nNext Commands\n"));
  console.log(`  ${a.white("ccjk context status")} ${a.dim("Review project context readiness")}`);
  console.log(`  ${a.white("ccjk memory --status")} ${a.dim("Inspect Claude and CCJK memory files")}`);
  console.log(`  ${a.white("ccjk memory --doctor")} ${a.dim("Run memory diagnostics and recommendations")}`);
  console.log(`  ${a.white("ccjk context --show")} ${a.dim("Preview loaded context layers")}`);
  console.log();
}
function describeMemorySyncState(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 project memory found";
  }
}
async function compressContext() {
  const t = getTranslation();
  console.log(a.green.bold(`
\u{1F5DC}\uFE0F  ${t("context.compressing")}
`));
  const analysis = analyzeDirectory(process.cwd());
  const duplicates = findDuplicates(analysis.files);
  const largeFiles = analysis.files.filter((f) => f.tokens > 1e3);
  const binaryFiles = analysis.files.filter((f) => f.type === "binary");
  let totalSavings = 0;
  if (duplicates.length > 0) {
    console.log(a.yellow(`${t("context.duplicatesFound")}: ${duplicates.length}
`));
    totalSavings += duplicates.length * 500;
  }
  if (largeFiles.length > 0) {
    console.log(a.yellow(`${t("context.largeFiles")}: ${largeFiles.length}
`));
    for (const file of largeFiles.slice(0, 5)) {
      console.log(`  ${a.white(file.path)} (${file.tokens.toLocaleString()} ${t("context.tokens")})`);
    }
    if (largeFiles.length > 5) {
      console.log(`  ${a.dim(`... and ${largeFiles.length - 5} more`)}`);
    }
    console.log();
    totalSavings += largeFiles.reduce((sum, f) => sum + Math.floor(f.tokens * 0.3), 0);
  }
  if (binaryFiles.length > 0) {
    console.log(a.yellow(`${t("context.binaryFiles")}: ${binaryFiles.length}
`));
    console.log(a.dim(`${t("context.binaryNote")}
`));
    totalSavings += binaryFiles.length * 200;
  }
  if (totalSavings > 0) {
    console.log(a.green(`${t("context.estimatedSavings")}: ${a.bold(totalSavings.toLocaleString())} ${t("context.tokens")}
`));
  } else {
    console.log(a.dim(`${t("context.noCompressionNeeded")}
`));
  }
}
async function optimizeContext() {
  const t = getTranslation();
  console.log(a.green.bold(`
\u26A1 ${t("context.optimizing")}
`));
  const analysis = analyzeDirectory(process.cwd());
  const suggestions = [];
  const largeFiles = analysis.files.filter((f) => f.tokens > 1e3);
  if (largeFiles.length > 0) {
    suggestions.push(`${t("context.suggestionLargeFiles")}: ${largeFiles.map((f) => f.path).join(", ")}`);
  }
  if (analysis.files.length > 20) {
    suggestions.push(`${t("context.suggestionManyFiles")}: ${analysis.files.length}`);
  }
  if (!existsSync(join(process.cwd(), ".claudeignore"))) {
    suggestions.push(t("context.suggestionClaudeignore"));
  }
  if (suggestions.length === 0) {
    console.log(a.green(`${t("context.optimized")}
`));
  } else {
    console.log(a.yellow(`${t("context.suggestions")}:
`));
    for (const suggestion of suggestions) {
      console.log(`  \u2022 ${suggestion}`);
    }
    console.log();
  }
}
function analyzeDirectory(dir) {
  const files = [];
  let totalTokens = 0;
  let totalSize = 0;
  try {
    const entries = readdirSync(dir, { withFileTypes: true });
    for (const entry of entries) {
      if (entry.isDirectory()) {
        if (["node_modules", ".git", "dist", "build", ".next", "target"].includes(entry.name)) {
          continue;
        }
        continue;
      }
      const filePath = join(dir, entry.name);
      const fileType = getFileType(entry.name);
      if (fileType === "binary") {
        continue;
      }
      try {
        const stats = lstatSync(filePath);
        const content = readFileSync(filePath, "utf-8");
        const tokens = estimateTokens(content);
        files.push({
          path: filePath,
          size: stats.size,
          tokens,
          type: fileType
        });
        totalTokens += tokens;
        totalSize += stats.size;
      } catch {
      }
    }
  } catch {
  }
  const largestFiles = [...files].sort((a, b) => b.tokens - a.tokens);
  return {
    files,
    totalTokens,
    totalSize,
    largestFiles
  };
}
function findContextFiles(dir) {
  const contextFiles = [];
  const contextPatterns = [
    "CLAUDE.md",
    "README.md",
    "package.json",
    "tsconfig.json",
    ".gitignore",
    ".claudeignore"
  ];
  try {
    const entries = readdirSync(dir);
    for (const entry of entries) {
      if (contextPatterns.includes(entry)) {
        contextFiles.push(join(dir, entry));
      }
    }
  } catch {
  }
  return contextFiles;
}
function findDuplicates(files) {
  const seen = /* @__PURE__ */ new Map();
  const duplicates = [];
  for (const file of files) {
    const name = file.path.split("/").pop() || file.path;
    if (!seen.has(name)) {
      seen.set(name, []);
    }
    seen.get(name).push(file);
  }
  for (const [, group] of seen) {
    if (group.length > 1) {
      duplicates.push(...group.slice(1));
    }
  }
  return duplicates;
}
function getFileType(filename) {
  const ext = filename.split(".").pop()?.toLowerCase();
  if (["ts", "tsx", "js", "jsx", "py", "rs", "go", "java", "c", "cpp", "h", "hpp"].includes(ext || "")) {
    return "code";
  }
  if (["md", "markdown", "txt"].includes(ext || "")) {
    return "markdown";
  }
  if (["json", "yaml", "yml", "toml", "xml"].includes(ext || "")) {
    return "text";
  }
  if (["png", "jpg", "jpeg", "gif", "ico", "pdf", "zip", "tar", "gz"].includes(ext || "")) {
    return "binary";
  }
  return "text";
}
function estimateTokens(text) {
  const chineseChars = (text.match(/[\u4E00-\u9FA5]/g) || []).length;
  const nonChineseChars = text.length - chineseChars;
  return Math.ceil(chineseChars / 2 + nonChineseChars / 4);
}
function formatBytes(bytes) {
  if (bytes === 0)
    return "0 B";
  const k = 1024;
  const sizes = ["B", "KB", "MB", "GB"];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  return `${Number.parseFloat((bytes / k ** i).toFixed(1))} ${sizes[i]}`;
}
async function handleContextCommand(args) {
  const [action, ..._rest] = args;
  switch (action) {
    case "analyze":
      await analyzeContext();
      break;
    case "status":
      await showContextStatus();
      break;
    case "compress":
      await compressContext();
      break;
    case "optimize":
      await optimizeContext();
      break;
    default:
      showContextHelp();
  }
}
function showContextHelp() {
  console.log(a.green.bold("\n\u{1F4DD} Context Commands\n"));
  console.log(a.white("  ccjk context analyze   ") + a.dim("Analyze context usage"));
  console.log(a.white("  ccjk context status    ") + a.dim("Show context status"));
  console.log(a.white("  ccjk context compress  ") + a.dim("Compress context"));
  console.log(a.white("  ccjk context optimize   ") + a.dim("Optimize context"));
  console.log();
}

async function contextBuild(options = {}) {
  const {
    target: _target = "claude-code",
    output = ".",
    force: _force = false,
    merge = false,
    projectName,
    projectDescription
  } = options;
  console.log("\u{1F50D} Analyzing project...");
  const intelligence = await analyzeProject(".");
  console.log("\u2705 Analysis complete");
  console.log(`   Languages: ${intelligence.stack.languages.join(", ")}`);
  console.log(`   Frameworks: ${intelligence.stack.frameworks.map((f) => f.name).join(", ")}`);
  console.log(`   Commands: ${intelligence.commands.length}`);
  console.log("");
  console.log("\u{1F4E6} Building context pack...");
  const contextPack = buildContextPack(intelligence, {
    projectName,
    projectDescription,
    includeCommands: true,
    includeRepoMap: true
  });
  const outputPath = join(output, "CLAUDE.md");
  if (merge) {
    try {
      await readFile(outputPath, "utf-8");
      console.log("\u{1F4DD} Merging with existing CLAUDE.md...");
    } catch {
    }
  }
  await writeClaudeContext(contextPack, outputPath);
  console.log(`\u2705 Context pack written to: ${outputPath}`);
}
async function contextRefresh() {
  console.log("\u{1F504} Refreshing context pack...");
  await contextBuild({ force: true, merge: true });
}
async function contextDoctor() {
  console.log("\u{1F50D} Running context health check...");
  const intelligence = await analyzeProject(".");
  console.log("\n\u{1F4CA} Project Health:");
  console.log(`   \u2705 Languages detected: ${intelligence.stack.languages.length}`);
  console.log(`   \u2705 Frameworks detected: ${intelligence.stack.frameworks.length}`);
  console.log(`   \u2705 Commands detected: ${intelligence.commands.length}`);
  console.log(`   \u2705 Directories scanned: ${intelligence.repoMap.directories.length}`);
  if (intelligence.commands.length === 0) {
    console.log("\n\u26A0\uFE0F  Warning: No commands detected. Consider adding package.json scripts.");
  }
  if (intelligence.stack.frameworks.length === 0) {
    console.log("\n\u26A0\uFE0F  Warning: No frameworks detected. Context may be generic.");
  }
  console.log("\n\u2705 Context health check complete");
}
async function contextCommand(options = {}) {
  if (options.action && ["analyze", "compress", "optimize", "status"].includes(options.action)) {
    await handleContextCommand([options.action]);
    return;
  }
  if (options.action === "refresh") {
    await contextRefresh();
    return;
  }
  if (options.action === "doctor") {
    await contextDoctor();
    return;
  }
  await contextBuild(options);
}

export { contextBuild, contextCommand, contextDoctor, contextRefresh };
