import a from './index5.mjs';
import { existsSync, readFileSync } from 'node:fs';
import process__default from 'node:process';
import { SETTINGS_FILE } from './constants.mjs';
import { j as join } from '../shared/ccjk.bQ7Dh1g4.mjs';
import { r as runHealthCheck } from '../shared/ccjk.Dxgd2vjc.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:os';
import './index2.mjs';
import 'node:url';
import './memory-check.mjs';
import 'node:path';
import 'fs';
import 'constants';
import 'stream';
import 'util';
import 'assert';
import 'path';
import './memory-paths.mjs';
import '../shared/ccjk.BBtCGd_g.mjs';
import './index3.mjs';
import './fs-operations.mjs';
import 'node:crypto';
import 'node:fs/promises';

function analyzeProject(root) {
  const cwd = process__default.cwd();
  const profile = {
    language: "unknown",
    frameworks: [],
    packageManager: "unknown",
    hasCI: false,
    hasDocker: false,
    hasMCP: false,
    hasClaudeMd: false,
    isMonorepo: false,
    tags: []
  };
  const pkgPath = join(cwd, "package.json");
  let pkg = null;
  if (existsSync(pkgPath)) {
    try {
      pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
      profile.projectName = pkg?.name;
    } catch {
    }
  }
  profile.language = detectLanguage(cwd, pkg);
  profile.packageManager = detectPackageManager(cwd);
  profile.frameworks = detectFrameworks(cwd, pkg);
  profile.testFramework = detectTestFramework(cwd, pkg);
  profile.buildTool = detectBuildTool(cwd, pkg);
  profile.hasCI = existsSync(join(cwd, ".github/workflows")) || existsSync(join(cwd, ".gitlab-ci.yml")) || existsSync(join(cwd, ".circleci")) || existsSync(join(cwd, "Jenkinsfile"));
  profile.hasDocker = existsSync(join(cwd, "Dockerfile")) || existsSync(join(cwd, "docker-compose.yml")) || existsSync(join(cwd, "docker-compose.yaml"));
  profile.hasMCP = checkMcpConfigured();
  profile.hasClaudeMd = existsSync(join(cwd, "CLAUDE.md"));
  profile.isMonorepo = existsSync(join(cwd, "pnpm-workspace.yaml")) || existsSync(join(cwd, "lerna.json")) || pkg?.workspaces != null;
  profile.tags = generateTags(profile);
  return profile;
}
function detectLanguage(cwd, pkg) {
  if (existsSync(join(cwd, "tsconfig.json")) || pkg?.devDependencies?.typescript)
    return "typescript";
  if (existsSync(join(cwd, "pyproject.toml")) || existsSync(join(cwd, "setup.py")))
    return "python";
  if (existsSync(join(cwd, "go.mod")))
    return "go";
  if (existsSync(join(cwd, "Cargo.toml")))
    return "rust";
  if (existsSync(join(cwd, "Gemfile")))
    return "ruby";
  if (existsSync(join(cwd, "pom.xml")) || existsSync(join(cwd, "build.gradle")))
    return "java";
  if (existsSync(join(cwd, "Package.swift")))
    return "swift";
  if (pkg)
    return "javascript";
  return "unknown";
}
function detectPackageManager(cwd) {
  if (existsSync(join(cwd, "pnpm-lock.yaml")) || existsSync(join(cwd, "pnpm-workspace.yaml")))
    return "pnpm";
  if (existsSync(join(cwd, "yarn.lock")))
    return "yarn";
  if (existsSync(join(cwd, "bun.lockb")) || existsSync(join(cwd, "bun.lock")))
    return "bun";
  if (existsSync(join(cwd, "package-lock.json")))
    return "npm";
  return "unknown";
}
function detectFrameworks(_cwd, pkg) {
  const frameworks = [];
  const allDeps = { ...pkg?.dependencies, ...pkg?.devDependencies };
  if (allDeps?.react || allDeps?.["react-dom"])
    frameworks.push("react");
  if (allDeps?.vue)
    frameworks.push("vue");
  if (allDeps?.svelte)
    frameworks.push("svelte");
  if (allDeps?.angular || allDeps?.["@angular/core"])
    frameworks.push("angular");
  if (allDeps?.next)
    frameworks.push("nextjs");
  if (allDeps?.nuxt)
    frameworks.push("nuxt");
  if (allDeps?.astro)
    frameworks.push("astro");
  if (allDeps?.express)
    frameworks.push("express");
  if (allDeps?.fastify)
    frameworks.push("fastify");
  if (allDeps?.koa)
    frameworks.push("koa");
  if (allDeps?.hono)
    frameworks.push("hono");
  if (allDeps?.["@nestjs/core"])
    frameworks.push("nestjs");
  if (allDeps?.electron)
    frameworks.push("electron");
  if (allDeps?.["@tauri-apps/api"])
    frameworks.push("tauri");
  if (allDeps?.["react-native"])
    frameworks.push("react-native");
  if (allDeps?.cac || allDeps?.commander || allDeps?.yargs)
    frameworks.push("cli");
  return frameworks;
}
function detectTestFramework(cwd, pkg) {
  const allDeps = { ...pkg?.dependencies, ...pkg?.devDependencies };
  if (allDeps?.vitest || existsSync(join(cwd, "vitest.config.ts")))
    return "vitest";
  if (allDeps?.jest || existsSync(join(cwd, "jest.config.js")))
    return "jest";
  if (allDeps?.mocha)
    return "mocha";
  if (allDeps?.playwright || allDeps?.["@playwright/test"])
    return "playwright";
  if (allDeps?.cypress)
    return "cypress";
  if (existsSync(join(cwd, "pytest.ini")) || existsSync(join(cwd, "conftest.py")))
    return "pytest";
  return void 0;
}
function detectBuildTool(cwd, pkg) {
  const allDeps = { ...pkg?.dependencies, ...pkg?.devDependencies };
  if (allDeps?.vite || existsSync(join(cwd, "vite.config.ts")))
    return "vite";
  if (allDeps?.webpack)
    return "webpack";
  if (allDeps?.esbuild)
    return "esbuild";
  if (allDeps?.unbuild)
    return "unbuild";
  if (allDeps?.rollup)
    return "rollup";
  if (allDeps?.turbo || existsSync(join(cwd, "turbo.json")))
    return "turbo";
  return void 0;
}
function checkMcpConfigured() {
  try {
    if (!existsSync(SETTINGS_FILE))
      return false;
    const settings = JSON.parse(readFileSync(SETTINGS_FILE, "utf-8"));
    return Object.keys(settings.mcpServers || {}).length > 0;
  } catch {
    return false;
  }
}
function generateTags(profile) {
  const tags = [];
  tags.push(profile.language);
  tags.push(...profile.frameworks);
  if (profile.testFramework)
    tags.push(profile.testFramework);
  if (profile.buildTool)
    tags.push(profile.buildTool);
  if (profile.packageManager !== "unknown")
    tags.push(profile.packageManager);
  if (profile.hasCI)
    tags.push("ci");
  if (profile.hasDocker)
    tags.push("docker");
  if (profile.isMonorepo)
    tags.push("monorepo");
  if (profile.frameworks.some((f) => ["react", "vue", "svelte", "angular"].includes(f)))
    tags.push("frontend");
  if (profile.frameworks.some((f) => ["express", "fastify", "koa", "nestjs", "hono"].includes(f)))
    tags.push("backend");
  if (profile.frameworks.some((f) => ["nextjs", "nuxt", "astro"].includes(f)))
    tags.push("fullstack");
  if (profile.frameworks.includes("cli"))
    tags.push("cli-tool");
  return [...new Set(tags)];
}

const SKILL_RULES = [
  {
    tags: ["typescript", "javascript", "python", "go", "rust", "ruby", "java"],
    skill: { id: "git-commit", name: "Smart Git Commit", description: "AI-powered conventional commit messages", reason: "Every project needs good commits", category: "git" }
  },
  {
    tags: ["typescript", "javascript", "python", "go", "rust"],
    skill: { id: "code-review", name: "Code Review", description: "Two-phase deep code review", reason: "Catch bugs before they ship", category: "review" }
  },
  {
    tags: ["react", "vue", "svelte", "angular", "frontend"],
    skill: { id: "component-gen", name: "Component Generator", description: "Generate UI components with tests", reason: "Frontend framework detected", category: "dev" }
  },
  {
    tags: ["express", "fastify", "koa", "nestjs", "hono", "backend"],
    skill: { id: "api-design", name: "API Design", description: "Design RESTful/GraphQL APIs", reason: "Backend framework detected", category: "dev" }
  },
  {
    tags: ["backend", "fullstack"],
    skill: { id: "security-audit", name: "Security Audit", description: "Check for common vulnerabilities", reason: "Server-side code needs security review", category: "review" }
  },
  {
    tags: ["vitest", "jest", "pytest", "mocha"],
    skill: { id: "tdd-workflow", name: "TDD Workflow", description: "Test-driven development cycle", reason: "Test framework detected", category: "testing" }
  },
  {
    tags: ["playwright", "cypress"],
    skill: { id: "e2e-helper", name: "E2E Test Helper", description: "Generate end-to-end tests", reason: "E2E framework detected", category: "testing" }
  },
  {
    tags: ["docker"],
    skill: { id: "docker-optimize", name: "Docker Optimizer", description: "Optimize Dockerfile", reason: "Docker detected", category: "devops" }
  },
  {
    tags: ["ci"],
    skill: { id: "ci-pipeline", name: "CI Pipeline", description: "Optimize CI/CD pipeline", reason: "CI configuration detected", category: "devops" }
  },
  {
    tags: ["cli-tool", "cli"],
    skill: { id: "cli-ux", name: "CLI UX Design", description: "Better CLI interfaces", reason: "CLI tool detected", category: "dev" }
  },
  {
    tags: ["monorepo"],
    skill: { id: "monorepo-manage", name: "Monorepo Manager", description: "Manage packages and releases", reason: "Monorepo detected", category: "dev" }
  },
  {
    tags: ["typescript", "javascript", "python"],
    skill: { id: "doc-gen", name: "Documentation Generator", description: "Generate API docs and README", reason: "Good docs improve maintainability", category: "docs" }
  },
  {
    tags: ["react", "vue", "nextjs", "nuxt", "frontend"],
    skill: { id: "perf-audit", name: "Performance Audit", description: "Bundle size and Core Web Vitals", reason: "Frontend performance matters", category: "review" }
  },
  {
    tags: ["nextjs", "nuxt", "astro", "fullstack"],
    skill: { id: "fullstack-debug", name: "Fullstack Debugger", description: "Debug across client/server boundary", reason: "Fullstack framework detected", category: "debug" }
  }
];
const MCP_RULES = [
  {
    tags: ["typescript", "javascript", "python", "go", "rust", "ruby", "java"],
    mcp: { id: "context7", name: "Context7", description: "Up-to-date library docs", reason: "Essential for accurate API usage" }
  },
  {
    tags: ["playwright", "frontend", "fullstack"],
    mcp: { id: "playwright", name: "Playwright MCP", description: "Browser automation", reason: "Frontend/E2E project detected" }
  },
  {
    tags: ["backend", "fullstack", "express", "fastify", "nestjs"],
    mcp: { id: "sqlite", name: "SQLite MCP", description: "Local database", reason: "Backend project detected" }
  },
  {
    tags: ["typescript", "javascript", "python", "go", "rust"],
    mcp: { id: "mcp-search", name: "Web Search", description: "Search for docs and solutions", reason: "Quick access to online resources" }
  }
];
function matchSkills(profile) {
  const results = [];
  const seen = /* @__PURE__ */ new Set();
  for (const rule of SKILL_RULES) {
    if (seen.has(rule.skill.id))
      continue;
    const matchingTags = rule.tags.filter((t) => profile.tags.includes(t));
    if (matchingTags.length === 0)
      continue;
    const matchScore = Math.min(100, Math.round(matchingTags.length / rule.tags.length * 100) + 20);
    results.push({ ...rule.skill, matchScore });
    seen.add(rule.skill.id);
  }
  results.sort((a, b) => b.matchScore - a.matchScore);
  return results;
}
function matchMcpServices(profile) {
  const results = [];
  const seen = /* @__PURE__ */ new Set();
  for (const rule of MCP_RULES) {
    if (seen.has(rule.mcp.id))
      continue;
    const matchingTags = rule.tags.filter((t) => profile.tags.includes(t));
    if (matchingTags.length === 0)
      continue;
    const matchScore = Math.min(100, Math.round(matchingTags.length / rule.tags.length * 100) + 20);
    results.push({ ...rule.mcp, matchScore });
    seen.add(rule.mcp.id);
  }
  results.sort((a, b) => b.matchScore - a.matchScore);
  return results;
}
function getRecommendations(profile) {
  const skills = matchSkills(profile);
  const mcpServices = matchMcpServices(profile);
  const parts = [];
  if (profile.language !== "unknown")
    parts.push(profile.language);
  parts.push(...profile.frameworks.slice(0, 3));
  const stackDesc = parts.join(" + ") || "your project";
  return {
    skills,
    mcpServices,
    summary: `Found ${skills.length} skills and ${mcpServices.length} MCP services for ${stackDesc}`
  };
}

async function executeRecommendation(rec) {
  if (!rec.command) {
    return { success: false, message: "No command available" };
  }
  try {
    const parts = rec.command.split(" ");
    const cmd = parts[0];
    const args = parts.slice(1);
    if (cmd === "ccjk") {
      return await runCcjkCommand(args);
    }
    const { x } = await import('./main.mjs');
    const result = await x(cmd, args, { throwOnError: false });
    return {
      success: result.exitCode === 0,
      message: result.exitCode === 0 ? "Applied" : `Failed: ${result.stderr}`
    };
  } catch (error) {
    return { success: false, message: `Error: ${error instanceof Error ? error.message : String(error)}` };
  }
}
async function runCcjkCommand(args) {
  const sub = args[0];
  try {
    if (sub === "init") {
      const { init } = await import('./init.mjs').then(function (n) { return n.c; });
      await init({ skipBanner: true, skipPrompt: true });
      return { success: true, message: "Initialization complete" };
    }
    if (sub === "ccjk:mcp" || sub === "ccjk-mcp") {
      const { ccjkMcp } = await import('./ccjk-mcp.mjs');
      await ccjkMcp({ interactive: false, dryRun: false, json: false });
      return { success: true, message: "MCP services configured" };
    }
    if (sub === "ccjk:skills" || sub === "ccjk-skills") {
      const { ccjkSkills } = await import('./ccjk-skills.mjs');
      await ccjkSkills({ interactive: false, dryRun: false, json: false });
      return { success: true, message: "Skills installed" };
    }
    if (sub === "ccjk:agents" || sub === "ccjk-agents") {
      const { ccjkAgents } = await import('./ccjk-agents.mjs');
      await ccjkAgents({ list: false, json: false });
      return { success: true, message: "Agents configured" };
    }
    if (sub === "doctor") {
      const { doctor } = await import('./doctor.mjs');
      await doctor({});
      return { success: true, message: "Doctor check complete" };
    }
    const { x } = await import('./main.mjs');
    const result = await x("ccjk", args, { throwOnError: false });
    return { success: result.exitCode === 0, message: result.exitCode === 0 ? "Done" : "Failed" };
  } catch (error) {
    return { success: false, message: `Error: ${error instanceof Error ? error.message : String(error)}` };
  }
}
async function boost(options = {}) {
  console.log(a.cyan.bold("\n\u{1F680} CCJK Boost - One-Click Optimization\n"));
  const ora = (await import('./index8.mjs')).default;
  let spinner = ora("Analyzing your setup...").start();
  const [report, profile] = await Promise.all([
    runHealthCheck(),
    Promise.resolve(analyzeProject())
  ]);
  const { skills: recSkills } = getRecommendations(profile);
  spinner.succeed(`Current score: ${a.bold(String(report.totalScore))}/100 (Grade ${report.grade})`);
  const actions = [];
  for (const rec of report.recommendations) {
    if (rec.command) {
      actions.push({ label: `${rec.title}: ${rec.description}`, rec });
    }
  }
  if (recSkills.length > 0 && !report.results.find((r) => r.name === "Skills" && r.status === "pass")) {
    actions.push({
      label: `Install ${recSkills.length} recommended skills for ${profile.language}`,
      rec: { priority: "medium", title: "Install Skills", description: `${recSkills.length} skills match your project`, command: "ccjk ccjk:skills", category: "skills" }
    });
  }
  if (actions.length === 0) {
    console.log(a.green("\n\u2728 Your setup is already optimized! Score: ") + a.green.bold(`${report.totalScore}/100`));
    console.log(a.gray('Run "ccjk status" for detailed breakdown.\n'));
    return;
  }
  console.log(a.yellow(`
\u{1F4CB} ${actions.length} optimization${actions.length > 1 ? "s" : ""} available:
`));
  for (const a$1 of actions) {
    const priority = a$1.rec.priority === "high" ? a.red("[HIGH]") : a.yellow("[MED]");
    console.log(`  ${priority} ${a$1.label}`);
    if (a$1.rec.command)
      console.log(`         ${a.gray(a$1.rec.command)}`);
  }
  if (options.dryRun) {
    console.log(a.gray("\n--dry-run: No changes applied.\n"));
    return;
  }
  let selectedActions = actions;
  if (!options.yes) {
    const { default: inquirer } = await import('./index6.mjs').then(function (n) { return n.c; });
    const { selected } = await inquirer.prompt([{
      type: "checkbox",
      name: "selected",
      message: "Select optimizations to apply:",
      choices: actions.map((a, i) => ({
        name: `${a.rec.priority === "high" ? "[HIGH] " : "[MED]  "}${a.label}`,
        value: i,
        checked: a.rec.priority === "high"
        // pre-check high priority
      }))
    }]);
    if (!selected.length) {
      console.log(a.gray("\nNothing selected. Cancelled.\n"));
      return;
    }
    selectedActions = selected.map((i) => actions[i]);
  }
  console.log("");
  let applied = 0;
  let failed = 0;
  for (const action of selectedActions) {
    spinner = ora(action.label).start();
    try {
      const result = await executeRecommendation(action.rec);
      if (result.success) {
        spinner.succeed(action.label);
        applied++;
      } else {
        spinner.warn(`${action.label} ${a.gray(`(${result.message})`)}`);
        failed++;
      }
    } catch {
      spinner.fail(action.label);
      failed++;
    }
  }
  console.log("");
  spinner = ora("Recalculating score...").start();
  const newReport = await runHealthCheck();
  spinner.stop();
  const delta = newReport.totalScore - report.totalScore;
  const deltaStr = delta > 0 ? a.green(`+${delta}`) : delta < 0 ? a.red(String(delta)) : "\xB10";
  console.log(a.cyan.bold("\n\u{1F4CA} Results"));
  console.log(`   Applied: ${a.green(String(applied))}  Failed: ${failed > 0 ? a.red(String(failed)) : a.gray("0")}`);
  console.log(`   Score: ${a.bold(String(report.totalScore))} \u2192 ${a.bold(String(newReport.totalScore))} (${deltaStr})`);
  console.log(`   Grade: ${report.grade} \u2192 ${a.bold(newReport.grade)}`);
  if (newReport.totalScore >= 80) {
    console.log(a.green("\n   \u2728 Excellent setup! Getting the most out of Claude Code.\n"));
  } else {
    console.log(a.yellow(`
   Run ${a.cyan("ccjk status")} for remaining recommendations.
`));
  }
}

export { boost };
