import { existsSync, readFileSync } from 'node:fs';
import process__default from 'node:process';
import a from './index5.mjs';
import { g as getRuntimeCapabilityDescriptor } from '../shared/ccjk.lG3ccFjm.mjs';
import { r as resolveCodeType, s as scanProject } from './code-type-resolver.mjs';
import { CLAVUE_CONFIG_FILE, CLAVUE_SETTINGS_FILE, SETTINGS_FILE } from './constants.mjs';
import { MetricsDisplay } from './metrics-display.mjs';
import { getContextPersistence } from './persistence.mjs';
import { r as runHealthCheck } from '../shared/ccjk.Dxgd2vjc.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:child_process';
import 'node:os';
import 'node:path';
import 'node:util';
import './index6.mjs';
import 'node:readline';
import 'stream';
import 'node:tty';
import 'node:async_hooks';
import '../shared/ccjk.Cjgrln_h.mjs';
import 'tty';
import 'fs';
import 'child_process';
import 'node:crypto';
import 'buffer';
import 'string_decoder';
import './json-config.mjs';
import '../shared/ccjk.RyizuzOI.mjs';
import './fs-operations.mjs';
import 'node:fs/promises';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import './platform.mjs';
import './main.mjs';
import 'module';
import 'node:stream';
import './index2.mjs';
import 'node:url';
import './ccjk-config.mjs';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import 'better-sqlite3';
import './memory-check.mjs';
import 'constants';
import 'util';
import 'assert';
import 'path';
import './memory-paths.mjs';

const GRADE_COLORS = {
  S: (s) => a.magenta.bold(s),
  A: (s) => a.green.bold(s),
  B: (s) => a.cyan.bold(s),
  C: (s) => a.yellow.bold(s),
  D: (s) => a.red(s),
  F: (s) => a.red.bold(s)
};
const STATUS_ICONS = {
  pass: a.green("\u2713"),
  warn: a.yellow("\u26A0"),
  fail: a.red("\u2717")
};
const INSTALLED = a.green("\u2713");
const MISSING = a.gray("\u2212");
function label(text) {
  return a.gray(text);
}
function val(text) {
  return a.white(text);
}
function heading(text) {
  return a.cyan.bold(text);
}
function divider() {
  return a.gray("\u2500".repeat(44));
}
function renderScoreBar(score) {
  const filled = Math.round(score / 5);
  const empty = 20 - filled;
  let bar = "";
  if (score >= 80)
    bar = a.green("\u2588".repeat(filled));
  else if (score >= 50)
    bar = a.yellow("\u2588".repeat(filled));
  else bar = a.red("\u2588".repeat(filled));
  bar += a.gray("\u2591".repeat(empty));
  return bar;
}
function getRuntimeSettingsPath(codeTool) {
  return codeTool === "clavue" ? CLAVUE_SETTINGS_FILE : SETTINGS_FILE;
}
function loadInstalledSettings(codeTool) {
  const settingsPath = getRuntimeSettingsPath(codeTool);
  try {
    if (!existsSync(settingsPath))
      return { mcpServers: {}, hooks: {} };
    const data = JSON.parse(readFileSync(settingsPath, "utf-8"));
    return {
      mcpServers: data.mcpServers || {},
      hooks: data.hooks || {}
    };
  } catch {
    return { mcpServers: {}, hooks: {} };
  }
}
async function loadSmartDefaults() {
  try {
    const { detectSmartDefaults } = await import('./code-type-resolver.mjs').then(function (n) { return n.b; });
    return await detectSmartDefaults();
  } catch {
    return null;
  }
}
function renderProjectSection(ctx) {
  const lines = [];
  lines.push(heading("Project"));
  const fields = [
    ["Language", ctx.language],
    ["Framework", ctx.framework],
    ["Test Runner", ctx.testRunner],
    ["Pkg Manager", ctx.packageManager],
    ["Linter", ctx.linter],
    ["Formatter", ctx.formatter],
    ["Database", ctx.database === "none" ? "none" : ctx.database]
  ];
  for (const [k, v] of fields) {
    const display = v === "none" || v === "unknown" ? a.gray(v) : val(v);
    lines.push(`  ${label(`${k}:`.padEnd(14))} ${display}`);
  }
  const flags = [];
  if (ctx.isMonorepo)
    flags.push("monorepo");
  if (ctx.hasDocker)
    flags.push("docker");
  if (ctx.hasCI)
    flags.push("CI");
  if (ctx.hasGitHooks)
    flags.push("git-hooks");
  if (ctx.usesConventionalCommits)
    flags.push("conventional-commits");
  if (flags.length > 0) {
    lines.push(`  ${label("Flags:".padEnd(14))} ${val(flags.join(", "))}`);
  }
  return lines;
}
function renderRuntimeSection(ctx, capability) {
  const lines = [];
  lines.push(heading("Runtime"));
  const rt = ctx.runtime;
  lines.push(`  ${label("Platform:".padEnd(14))} ${val(process__default.platform)} ${a.gray(`(${process__default.arch})`)}`);
  const envFlags = [];
  if (rt.isContainer)
    envFlags.push("container");
  if (rt.isHeadless)
    envFlags.push("headless");
  if (rt.isSSH)
    envFlags.push("SSH");
  if (rt.isCI)
    envFlags.push("CI");
  if (rt.isWSL)
    envFlags.push("WSL");
  if (envFlags.length > 0) {
    lines.push(`  ${label("Environment:".padEnd(14))} ${val(envFlags.join(", "))}`);
  } else {
    lines.push(`  ${label("Environment:".padEnd(14))} ${a.gray("standard")}`);
  }
  lines.push(`  ${label("Browser:".padEnd(14))} ${rt.hasBrowser ? a.green("available") : a.gray("unavailable")}`);
  if (capability) {
    const nativeFeatures = [
      capability.native.agentLoop && "agent-loop",
      capability.native.planTask && "plan/task",
      capability.native.subagents && "subagents",
      capability.native.slashCommands && "slash-commands",
      capability.native.mcp && "mcp",
      capability.native.permissions && "permissions",
      capability.native.memory && "memory",
      capability.native.ideIntegration && "ide",
      capability.native.worktree && "worktree",
      capability.native.statusline && "statusline"
    ].filter(Boolean);
    const managedByCcjk = [
      capability.managedByCcjk.providerProfiles && "profiles",
      capability.managedByCcjk.modelRouting && "models",
      capability.managedByCcjk.configSync && "config-sync",
      capability.managedByCcjk.permissionRepair && "permission-repair",
      capability.managedByCcjk.mcpBundles && "mcp-bundles",
      capability.managedByCcjk.doctor && "doctor"
    ].filter(Boolean);
    lines.push(`  ${label("Ownership:".padEnd(14))} ${val(capability.ownership)}`);
    lines.push(`  ${label("Native:".padEnd(14))} ${nativeFeatures.length > 0 ? val(nativeFeatures.join(", ")) : a.gray("none")}`);
    lines.push(`  ${label("CCJK:".padEnd(14))} ${managedByCcjk.length > 0 ? val(managedByCcjk.join(", ")) : a.gray("none")}`);
  }
  return lines;
}
function renderMcpSection(recommended, installed) {
  const lines = [];
  lines.push(heading("MCP Services"));
  const installedNames = Object.keys(installed);
  if (recommended.length === 0 && installedNames.length === 0) {
    lines.push(`  ${a.gray("No MCP services detected")}`);
    return lines;
  }
  const shown = /* @__PURE__ */ new Set();
  for (const svc of recommended) {
    const isInstalled = installedNames.some(
      (name) => name.toLowerCase().includes(svc.toLowerCase()) || svc.toLowerCase().includes(name.toLowerCase())
    );
    const icon = isInstalled ? INSTALLED : MISSING;
    lines.push(`  ${icon} ${isInstalled ? val(svc) : a.gray(svc)}`);
    shown.add(svc.toLowerCase());
  }
  for (const name of installedNames) {
    if (!shown.has(name.toLowerCase()) && !recommended.some((r) => r.toLowerCase() === name.toLowerCase())) {
      lines.push(`  ${INSTALLED} ${val(name)} ${a.gray("(extra)")}`);
    }
  }
  return lines;
}
function renderHooksSection(recommended, installed) {
  const lines = [];
  lines.push(heading("Hooks"));
  const installedEvents = Object.keys(installed);
  const hasAnyHooks = installedEvents.length > 0;
  if (recommended.length === 0 && !hasAnyHooks) {
    lines.push(`  ${a.gray("No hooks detected")}`);
    return lines;
  }
  for (const hookId of recommended) {
    const isInstalled = hasAnyHooks;
    const icon = isInstalled ? INSTALLED : MISSING;
    lines.push(`  ${icon} ${isInstalled ? val(hookId) : a.gray(hookId)}`);
  }
  if (hasAnyHooks) {
    const totalHookCount = installedEvents.reduce((sum, event) => {
      const eventHooks = installed[event];
      return sum + (Array.isArray(eventHooks) ? eventHooks.length : 0);
    }, 0);
    if (totalHookCount > 0) {
      lines.push(`  ${a.gray(`${totalHookCount} hook(s) across ${installedEvents.length} event(s)`)}`);
    }
  }
  return lines;
}
function getRuntimeSectionTitle(codeTool) {
  switch (codeTool) {
    case "clavue":
      return "clavue";
    case "codex":
      return "Codex";
    case "claude-code":
      return "Claude Code";
    default:
      return "Claude Runtime";
  }
}
function renderClaudeCodeSection(defaults, codeTool) {
  const lines = [];
  lines.push(heading(getRuntimeSectionTitle(codeTool)));
  const version = defaults?.claudeCodeVersion;
  lines.push(`  ${label("Version:".padEnd(14))} ${version ? val(version) : a.gray("not detected")}`);
  if (defaults?.nativeFeatures) {
    const nf = defaults.nativeFeatures;
    const features = [];
    if (nf.hooks)
      features.push("hooks");
    if (nf.memory)
      features.push("memory");
    if (nf.subagents)
      features.push("subagents");
    if (nf.toolSearch)
      features.push("tool-search");
    if (features.length > 0) {
      lines.push(`  ${label("Features:".padEnd(14))} ${val(features.join(", "))}`);
    }
  }
  try {
    const settingsPath = getRuntimeSettingsPath(codeTool);
    const clavuePath = CLAVUE_CONFIG_FILE;
    if (existsSync(settingsPath)) {
      const data = JSON.parse(readFileSync(settingsPath, "utf-8"));
      const env = data.env || {};
      const haiku = env.ANTHROPIC_DEFAULT_HAIKU_MODEL;
      const sonnet = env.ANTHROPIC_DEFAULT_SONNET_MODEL;
      const opus = env.ANTHROPIC_DEFAULT_OPUS_MODEL;
      const primary = data.model || env.ANTHROPIC_MODEL;
      const hasAdaptive = Boolean(haiku || sonnet || opus);
      if (codeTool === "clavue" && existsSync(clavuePath)) {
        try {
          const clavueData = JSON.parse(readFileSync(clavuePath, "utf-8"));
          const activeId = clavueData.clavueActiveProviderProfileId || clavueData.myclaudeActiveProviderProfileId;
          const profiles = Array.isArray(clavueData.clavueProviderProfiles) ? clavueData.clavueProviderProfiles : Array.isArray(clavueData.myclaudeProviderProfiles) ? clavueData.myclaudeProviderProfiles : [];
          const activeProfile = Array.isArray(profiles) ? profiles.find((profile) => String(profile?.id) === String(activeId)) : null;
          if (activeId) {
            lines.push(`  ${label("Provider:".padEnd(14))} ${val(`clavue/${activeId}`)}`);
          }
          if (activeProfile?.baseUrl) {
            lines.push(`  ${label("API Base:".padEnd(14))} ${val(activeProfile.baseUrl)}`);
          }
        } catch {
        }
      }
      if (codeTool !== "clavue" && data.model && hasAdaptive) {
        lines.push(`  ${label("Model:".padEnd(14))} ${a.red(data.model)} ${a.red("(overrides adaptive routing!)")}`);
        lines.push(`  ${label("".padEnd(14))} ${a.yellow("Run: ccjk boost --fix-model")}`);
      } else if (hasAdaptive) {
        lines.push(`  ${label("Routing:".padEnd(14))} ${a.green("adaptive")}`);
        if (primary)
          lines.push(`  ${label("  Primary:".padEnd(14))} ${val(primary)}`);
        if (haiku)
          lines.push(`  ${label("  Quick:".padEnd(14))} ${val(haiku)}`);
        if (sonnet)
          lines.push(`  ${label("  Standard:".padEnd(14))} ${val(sonnet)}`);
        if (opus)
          lines.push(`  ${label("  Complex:".padEnd(14))} ${val(opus)}`);
      } else if (primary) {
        lines.push(`  ${label("Model:".padEnd(14))} ${val(primary)}`);
      }
    }
  } catch {
  }
  return lines;
}
function renderCompressionMetricsSection(projectHash) {
  const lines = [];
  lines.push(heading("Compression Metrics"));
  try {
    const persistence = getContextPersistence();
    const stats = persistence.getCompressionMetricsStats(projectHash);
    if (stats.totalCompressions === 0) {
      lines.push(`  ${a.gray("No compression data available")}`);
      return lines;
    }
    lines.push(`  ${label("Total Saved:".padEnd(14))} ${a.green(MetricsDisplay.formatTokenCount(stats.totalTokensSaved))} tokens`);
    lines.push(`  ${label("Avg Reduction:".padEnd(14))} ${a.yellow(MetricsDisplay.formatRatio(stats.averageCompressionRatio))}`);
    lines.push(`  ${label("Cost Savings:".padEnd(14))} ${a.green.bold(MetricsDisplay.formatCost(stats.estimatedCostSavings))}`);
    if (stats.sessionStats && stats.sessionStats.compressions > 0) {
      lines.push(`  ${label("Session (24h):".padEnd(14))} ${a.white(stats.sessionStats.compressions)} compressions, ${a.green(MetricsDisplay.formatCost(stats.sessionStats.costSavings))} saved`);
    }
    return lines;
  } catch {
    lines.push(`  ${a.gray("Metrics unavailable")}`);
    return lines;
  }
}
function renderHealthSection(report, compact) {
  const lines = [];
  lines.push(heading("Brain Dashboard"));
  const gradeColor = GRADE_COLORS[report.grade] || ((s) => s);
  const scoreBar = renderScoreBar(report.totalScore);
  lines.push(`  ${label("Score:".padEnd(14))} ${scoreBar} ${gradeColor(report.grade)} ${a.gray(`(${report.totalScore}/100)`)}`);
  if (!compact) {
    lines.push("");
    for (const r of report.results) {
      const icon = STATUS_ICONS[r.status];
      const scoreText = a.gray(`${r.score}/${r.weight}`);
      lines.push(`  ${icon} ${r.name.padEnd(18)} ${scoreText.padEnd(10)} ${a.gray(r.message)}`);
      if (r.details?.length) {
        for (const detail of r.details) {
          lines.push(`     ${a.gray(detail)}`);
        }
      }
    }
  }
  if (report.recommendations.length > 0) {
    lines.push("");
    lines.push(a.yellow.bold("  Recommendations:"));
    for (const rec of report.recommendations.slice(0, 3)) {
      const priority = rec.priority === "high" ? a.red("!") : rec.priority === "medium" ? a.yellow("\u2022") : a.gray("\xB7");
      lines.push(`  ${priority} ${rec.title}`);
      if (rec.command) {
        lines.push(`    ${a.gray("\u2192")} ${a.cyan(rec.command)}  ${a.yellow("[fix]")}`);
      }
    }
  }
  return lines;
}
function suggestNextAction(health, _ctx) {
  const lines = [];
  lines.push(heading("Next Step"));
  const score = health.totalScore;
  const hasFailures = health.results.some((r) => r.status === "fail");
  const hasWarnings = health.results.some((r) => r.status === "warn");
  if (hasFailures) {
    const firstFail = health.results.find((r) => r.status === "fail");
    lines.push(`  ${a.red("\u2192")} Fix ${a.bold(firstFail.name)}: ${firstFail.message}`);
    if (firstFail.command) {
      lines.push(`    ${a.cyan(firstFail.command)}`);
    } else {
      lines.push(`    ${a.cyan("ccjk boost")} to auto-fix`);
    }
    return lines;
  }
  if (score < 60) {
    lines.push(`  ${a.yellow("\u2192")} Score is ${score}/100. Run ${a.cyan("ccjk boost")} to optimize.`);
    return lines;
  }
  if (hasWarnings) {
    const warnCount = health.results.filter((r) => r.status === "warn").length;
    lines.push(`  ${a.yellow("\u2192")} ${warnCount} warning${warnCount > 1 ? "s" : ""} remaining. Run ${a.cyan("ccjk boost --dry-run")} to preview fixes.`);
    return lines;
  }
  if (score >= 80) {
    lines.push(`  ${a.green("\u2192")} Setup looks great. Start coding or run ${a.cyan("ccjk brain status")} to check session.`);
  } else {
    lines.push(`  ${a.green("\u2192")} Almost there. Run ${a.cyan("ccjk boost")} to push past ${score}.`);
  }
  return lines;
}
async function statusCommand(options = {}) {
  try {
    const codeTool = await resolveCodeType();
    const [ctx, defaults, installed, health] = await Promise.all([
      scanProject(),
      loadSmartDefaults(),
      Promise.resolve(loadInstalledSettings(codeTool)),
      runHealthCheck()
    ]);
    const capability = getRuntimeCapabilityDescriptor(codeTool);
    if (options.json) {
      console.log(JSON.stringify({
        project: ctx,
        smartDefaults: defaults,
        installed,
        health,
        codeTool,
        capability
      }, null, 2));
      return;
    }
    const sections = [];
    sections.push(renderProjectSection(ctx));
    sections.push(renderRuntimeSection(ctx, capability));
    if (defaults) {
      sections.push(renderMcpSection(defaults.mcpServices, installed.mcpServers));
      sections.push(renderHooksSection(defaults.recommendedHooks, installed.hooks));
      sections.push(renderClaudeCodeSection(defaults, codeTool));
    } else {
      sections.push(renderMcpSection([], installed.mcpServers));
      sections.push(renderHooksSection([], installed.hooks));
      sections.push(renderClaudeCodeSection(null, codeTool));
    }
    sections.push(renderHealthSection(health, options.compact || false));
    try {
      sections.push(renderCompressionMetricsSection());
    } catch {
    }
    sections.push(suggestNextAction(health, ctx));
    console.log();
    for (let i = 0; i < sections.length; i++) {
      console.log(sections[i].join("\n"));
      if (i < sections.length - 1) {
        console.log();
        console.log(divider());
        console.log();
      }
    }
    console.log();
    const fixable = health.results.filter((r) => r.status !== "pass" && r.command);
    if (fixable.length > 0 && !options.json && options.fix) {
      const { autoFix } = await import('./auto-fixer.mjs');
      await autoFix(fixable, {
        autoApprove: options.yes,
        dryRun: options.dryRun
      });
    }
  } catch (error) {
    console.error(a.red("Error running status command:"), error);
    process__default.exit(1);
  }
}

export { statusCommand };
