import { existsSync, readFileSync, readdirSync, statSync, mkdirSync, writeFileSync } from 'node:fs';
import { j as join, d as dirname } from '../shared/ccjk.bQ7Dh1g4.mjs';
import { homedir } from 'node:os';
import { fileURLToPath } from 'node:url';

class ProjectAnalyzer {
  projectRoot;
  constructor(projectRoot = process.cwd()) {
    this.projectRoot = projectRoot;
  }
  /**
   * Analyze project and return comprehensive analysis
   */
  async analyze() {
    const packageJson = this.readPackageJson();
    const techStack = this.detectTechStack(packageJson);
    const projectType = this.detectProjectType(techStack, packageJson);
    const frameworks = this.detectFrameworks(packageJson);
    const hasTests = this.detectTestFramework(packageJson);
    const hasDatabase = this.detectDatabase(packageJson);
    const hasApi = this.detectApiEndpoints();
    const buildTool = this.detectBuildTool(packageJson);
    const cicd = this.detectCICD();
    const patterns = this.detectPatterns();
    const confidence = this.calculateConfidence(techStack, frameworks);
    return {
      projectRoot: this.projectRoot,
      projectType,
      techStack,
      frameworks,
      hasTests,
      hasDatabase,
      hasApi,
      buildTool,
      cicd,
      patterns,
      confidence,
      packageJson: packageJson ?? void 0
    };
  }
  /**
   * Read and parse package.json
   */
  readPackageJson() {
    const packageJsonPath = join(this.projectRoot, "package.json");
    if (!existsSync(packageJsonPath)) {
      return null;
    }
    try {
      const content = readFileSync(packageJsonPath, "utf-8");
      return JSON.parse(content);
    } catch {
      return null;
    }
  }
  /**
   * Detect technology stack from dependencies
   */
  detectTechStack(packageJson) {
    if (!packageJson) {
      return {
        languages: ["javascript"],
        runtime: "node",
        packageManager: this.detectPackageManager()
      };
    }
    const deps = {
      ...packageJson.dependencies,
      ...packageJson.devDependencies
    };
    const languages = [];
    let runtime = "node";
    if (deps.typescript || existsSync(join(this.projectRoot, "tsconfig.json"))) {
      languages.push("typescript");
    } else {
      languages.push("javascript");
    }
    if (existsSync(join(this.projectRoot, "deno.json")) || existsSync(join(this.projectRoot, "deno.jsonc"))) {
      runtime = "deno";
    }
    if (existsSync(join(this.projectRoot, "bun.lockb"))) {
      runtime = "bun";
    }
    return {
      languages,
      runtime,
      packageManager: this.detectPackageManager()
    };
  }
  /**
   * Detect package manager
   */
  detectPackageManager() {
    if (existsSync(join(this.projectRoot, "pnpm-lock.yaml"))) {
      return "pnpm";
    }
    if (existsSync(join(this.projectRoot, "yarn.lock"))) {
      return "yarn";
    }
    if (existsSync(join(this.projectRoot, "bun.lockb"))) {
      return "bun";
    }
    if (existsSync(join(this.projectRoot, "package-lock.json"))) {
      return "npm";
    }
    return "npm";
  }
  /**
   * Detect project type
   */
  detectProjectType(techStack, packageJson) {
    if (!packageJson) {
      return "unknown";
    }
    const deps = {
      ...packageJson.dependencies,
      ...packageJson.devDependencies
    };
    const hasFrontend = deps.react || deps.vue || deps["@angular/core"] || deps.svelte;
    const hasBackend = deps.express || deps.fastify || deps.koa || deps["@nestjs/core"] || deps.hapi;
    if (deps.next || deps.nuxt || deps["@remix-run/react"] || deps["@sveltejs/kit"]) {
      return "fullstack";
    }
    if (packageJson.bin || deps.commander || deps.yargs || deps.cac) {
      return "cli";
    }
    if (packageJson.main && !hasFrontend && !hasBackend) {
      return "library";
    }
    if (hasFrontend && hasBackend) {
      return "fullstack";
    }
    if (hasFrontend) {
      return "frontend";
    }
    if (hasBackend) {
      return "backend";
    }
    return "unknown";
  }
  /**
   * Detect frameworks
   */
  detectFrameworks(packageJson) {
    if (!packageJson) {
      return [];
    }
    const deps = {
      ...packageJson.dependencies,
      ...packageJson.devDependencies
    };
    const frameworks = [];
    if (deps.react)
      frameworks.push("react");
    if (deps.vue)
      frameworks.push("vue");
    if (deps["@angular/core"])
      frameworks.push("angular");
    if (deps.svelte)
      frameworks.push("svelte");
    if (deps.next)
      frameworks.push("next.js");
    if (deps.nuxt)
      frameworks.push("nuxt");
    if (deps["@remix-run/react"])
      frameworks.push("remix");
    if (deps["@sveltejs/kit"])
      frameworks.push("sveltekit");
    if (deps.express)
      frameworks.push("express");
    if (deps.fastify)
      frameworks.push("fastify");
    if (deps.koa)
      frameworks.push("koa");
    if (deps["@nestjs/core"])
      frameworks.push("nestjs");
    if (deps.hapi)
      frameworks.push("hapi");
    return frameworks;
  }
  /**
   * Detect test framework
   */
  detectTestFramework(packageJson) {
    if (!packageJson) {
      return false;
    }
    const deps = {
      ...packageJson.dependencies,
      ...packageJson.devDependencies
    };
    return !!(deps.vitest || deps.jest || deps.mocha || deps.ava || deps["@playwright/test"] || deps.cypress);
  }
  /**
   * Detect database usage
   */
  detectDatabase(packageJson) {
    if (!packageJson) {
      return false;
    }
    const deps = {
      ...packageJson.dependencies,
      ...packageJson.devDependencies
    };
    return !!(deps.prisma || deps["@prisma/client"] || deps.drizzle || deps["drizzle-orm"] || deps.typeorm || deps.sequelize || deps.mongoose || deps.pg || deps.mysql || deps.mysql2 || deps.sqlite3 || deps["better-sqlite3"]);
  }
  /**
   * Detect API endpoints
   */
  detectApiEndpoints() {
    const apiDirs = [
      "src/api",
      "src/routes",
      "api",
      "routes",
      "pages/api",
      // Next.js
      "app/api"
      // Next.js App Router
    ];
    return apiDirs.some((dir) => existsSync(join(this.projectRoot, dir)));
  }
  /**
   * Detect build tool
   */
  detectBuildTool(packageJson) {
    if (!packageJson) {
      return void 0;
    }
    const deps = {
      ...packageJson.dependencies,
      ...packageJson.devDependencies
    };
    if (deps.vite || existsSync(join(this.projectRoot, "vite.config.ts"))) {
      return "vite";
    }
    if (deps.webpack || existsSync(join(this.projectRoot, "webpack.config.js"))) {
      return "webpack";
    }
    if (deps.rollup || existsSync(join(this.projectRoot, "rollup.config.js"))) {
      return "rollup";
    }
    if (deps.esbuild) {
      return "esbuild";
    }
    if (deps.turbo || existsSync(join(this.projectRoot, "turbo.json"))) {
      return "turbo";
    }
    return void 0;
  }
  /**
   * Detect CI/CD configuration
   */
  detectCICD() {
    const cicd = [];
    if (existsSync(join(this.projectRoot, ".github", "workflows"))) {
      cicd.push("github-actions");
    }
    if (existsSync(join(this.projectRoot, ".gitlab-ci.yml"))) {
      cicd.push("gitlab-ci");
    }
    if (existsSync(join(this.projectRoot, ".circleci", "config.yml"))) {
      cicd.push("circleci");
    }
    if (existsSync(join(this.projectRoot, ".travis.yml"))) {
      cicd.push("travis-ci");
    }
    return cicd;
  }
  /**
   * Detect common patterns in the project
   */
  detectPatterns() {
    const patterns = [];
    if (existsSync(join(this.projectRoot, "packages")) || existsSync(join(this.projectRoot, "apps"))) {
      patterns.push("monorepo");
    }
    if (existsSync(join(this.projectRoot, "tsconfig.json"))) {
      patterns.push("typescript");
    }
    if (existsSync(join(this.projectRoot, ".eslintrc.js")) || existsSync(join(this.projectRoot, "eslint.config.js"))) {
      patterns.push("eslint");
    }
    if (existsSync(join(this.projectRoot, ".prettierrc")) || existsSync(join(this.projectRoot, "prettier.config.js"))) {
      patterns.push("prettier");
    }
    if (existsSync(join(this.projectRoot, "Dockerfile")) || existsSync(join(this.projectRoot, "docker-compose.yml"))) {
      patterns.push("docker");
    }
    if (existsSync(join(this.projectRoot, ".env.example")) || existsSync(join(this.projectRoot, ".env.local"))) {
      patterns.push("env-config");
    }
    return patterns;
  }
  /**
   * Calculate confidence score based on detected information
   */
  calculateConfidence(techStack, frameworks) {
    let confidence = 0.5;
    if (techStack.languages.length > 0)
      confidence += 0.1;
    if (techStack.runtime !== "unknown")
      confidence += 0.1;
    if (techStack.packageManager)
      confidence += 0.1;
    if (frameworks.length > 0)
      confidence += 0.1;
    if (frameworks.length > 2)
      confidence += 0.1;
    return Math.min(confidence, 1);
  }
  /**
   * Get file count in directory
   */
  getFileCount(dir) {
    try {
      if (!existsSync(dir)) {
        return 0;
      }
      let count = 0;
      const items = readdirSync(dir);
      for (const item of items) {
        const fullPath = join(dir, item);
        const stat = statSync(fullPath);
        if (stat.isDirectory()) {
          count += this.getFileCount(fullPath);
        } else {
          count++;
        }
      }
      return count;
    } catch {
      return 0;
    }
  }
}
async function analyzeProject(projectRoot) {
  const analyzer = new ProjectAnalyzer(projectRoot);
  return analyzer.analyze();
}

const __filename$1 = fileURLToPath(import.meta.url);
const __dirname$1 = dirname(__filename$1);
class ConfigGenerator {
  templatesDir;
  outputDir;
  constructor(templatesDir, outputDir) {
    this.templatesDir = templatesDir || join(__dirname$1, "..", "templates");
    this.outputDir = outputDir || join(homedir(), ".config", "claude");
  }
  /**
   * Generate configurations from template selection
   */
  async generate(selection) {
    const agentConfigs = await this.generateAgents(selection.agents);
    const skillConfigs = await this.generateSkills(selection.skills);
    return {
      agents: agentConfigs,
      skills: skillConfigs,
      summary: this.generateSummary(agentConfigs, skillConfigs)
    };
  }
  /**
   * Generate agent configurations
   */
  async generateAgents(agents) {
    const configs = [];
    for (const agent of agents) {
      const templatePath = join(this.templatesDir, "agents", agent.file);
      if (!existsSync(templatePath)) {
        console.warn(`Agent template not found: ${agent.file}`);
        continue;
      }
      const content = readFileSync(templatePath, "utf-8");
      const outputPath = join(this.outputDir, "agents", agent.file);
      configs.push({
        id: agent.id,
        path: outputPath,
        content
      });
    }
    return configs;
  }
  /**
   * Generate skill configurations
   */
  async generateSkills(skills) {
    const configs = [];
    for (const skill of skills) {
      const templatePath = join(this.templatesDir, "skills", skill.file);
      if (!existsSync(templatePath)) {
        console.warn(`Skill template not found: ${skill.file}`);
        continue;
      }
      const content = readFileSync(templatePath, "utf-8");
      const outputPath = join(this.outputDir, "skills", skill.file);
      configs.push({
        id: skill.id,
        path: outputPath,
        content
      });
    }
    return configs;
  }
  /**
   * Write configurations to disk
   */
  async write(config) {
    const agentsDir = join(this.outputDir, "agents");
    const skillsDir = join(this.outputDir, "skills");
    if (!existsSync(agentsDir)) {
      mkdirSync(agentsDir, { recursive: true });
    }
    if (!existsSync(skillsDir)) {
      mkdirSync(skillsDir, { recursive: true });
    }
    for (const agent of config.agents) {
      const dir = join(agent.path, "..");
      if (!existsSync(dir)) {
        mkdirSync(dir, { recursive: true });
      }
      writeFileSync(agent.path, agent.content, "utf-8");
    }
    for (const skill of config.skills) {
      const dir = join(skill.path, "..");
      if (!existsSync(dir)) {
        mkdirSync(dir, { recursive: true });
      }
      writeFileSync(skill.path, skill.content, "utf-8");
    }
  }
  /**
   * Generate summary
   */
  generateSummary(agents, skills) {
    const lines = [];
    lines.push("# Generated Configuration Summary\n");
    lines.push(`Generated at: ${(/* @__PURE__ */ new Date()).toISOString()}
`);
    lines.push("## Agents\n");
    for (const agent of agents) {
      lines.push(`- ${agent.id}: ${agent.path}`);
    }
    lines.push("\n## Skills\n");
    for (const skill of skills) {
      lines.push(`- ${skill.id}: ${skill.path}`);
    }
    lines.push("\n## Usage\n");
    lines.push("1. Agents are automatically loaded by Claude Code");
    lines.push("2. Skills can be triggered using their command triggers");
    lines.push("3. Use `claude` command to start coding with AI assistance");
    return lines.join("\n");
  }
}
async function generateConfigs(selection) {
  const generator = new ConfigGenerator();
  return generator.generate(selection);
}
async function writeConfigs(config) {
  const generator = new ConfigGenerator();
  await generator.write(config);
}

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
class TemplateSelector {
  templatesDir;
  constructor(templatesDir) {
    this.templatesDir = templatesDir || join(__dirname, "..", "..", "..", "templates");
  }
  /**
   * Select templates based on project analysis
   */
  async select(analysis) {
    const agents = await this.selectAgents(analysis);
    const skills = await this.selectSkills(analysis);
    return {
      agents,
      skills,
      reasoning: this.generateReasoning(analysis, agents, skills)
    };
  }
  /**
   * Select agent templates
   */
  async selectAgents(analysis) {
    const selectedAgents = [];
    const agentIndex = this.loadAgentIndex();
    switch (analysis.projectType) {
      case "frontend":
        selectedAgents.push(
          ...this.findAgentsByCategory(agentIndex, "frontend")
        );
        break;
      case "backend":
        selectedAgents.push(
          ...this.findAgentsByCategory(agentIndex, "backend")
        );
        break;
      case "fullstack":
        selectedAgents.push(
          ...this.findAgentsByCategory(agentIndex, "fullstack")
        );
        selectedAgents.push(
          ...this.findAgentsByCategory(agentIndex, "frontend").slice(0, 1),
          ...this.findAgentsByCategory(agentIndex, "backend").slice(0, 1)
        );
        break;
      case "cli":
      case "library":
        selectedAgents.push(
          ...this.findAgentsByCategory(agentIndex, "backend")
        );
        break;
    }
    if (analysis.hasTests) {
      selectedAgents.push(
        ...this.findAgentsByCategory(agentIndex, "testing")
      );
    }
    if (analysis.cicd && analysis.cicd.length > 0) {
      selectedAgents.push(
        ...this.findAgentsByCategory(agentIndex, "devops")
      );
    }
    if (analysis.hasApi || analysis.hasDatabase) {
      selectedAgents.push(
        ...this.findAgentsByCategory(agentIndex, "security")
      );
    }
    return this.deduplicateAndSort(selectedAgents);
  }
  /**
   * Select skill templates
   */
  async selectSkills(analysis) {
    const selectedSkills = [];
    const skillIndex = this.loadSkillIndex();
    selectedSkills.push(
      ...this.findSkillsByCategory(skillIndex, "git")
    );
    selectedSkills.push(
      ...this.findSkillsByCategory(skillIndex, "code-quality")
    );
    if (analysis.hasTests) {
      selectedSkills.push(
        ...this.findSkillsByIds(skillIndex, ["generate-tests"])
      );
    }
    if (analysis.hasApi) {
      selectedSkills.push(
        ...this.findSkillsByIds(skillIndex, ["api-docs"])
      );
    }
    if (analysis.hasDatabase) {
      selectedSkills.push(
        ...this.findSkillsByIds(skillIndex, ["database-migration"])
      );
    }
    if (analysis.projectType === "frontend" || analysis.projectType === "fullstack") {
      selectedSkills.push(
        ...this.findSkillsByIds(skillIndex, ["performance-optimization"])
      );
    }
    if (analysis.packageJson) {
      selectedSkills.push(
        ...this.findSkillsByIds(skillIndex, ["dependency-update"])
      );
    }
    selectedSkills.push(
      ...this.findSkillsByIds(skillIndex, ["refactor-code"])
    );
    return this.deduplicateAndSort(selectedSkills);
  }
  /**
   * Load agent index
   */
  loadAgentIndex() {
    try {
      const indexPath = join(this.templatesDir, "agents", "index.json");
      const content = readFileSync(indexPath, "utf-8");
      return JSON.parse(content);
    } catch {
      return { templates: [] };
    }
  }
  /**
   * Load skill index
   */
  loadSkillIndex() {
    try {
      const indexPath = join(this.templatesDir, "skills", "index.json");
      const content = readFileSync(indexPath, "utf-8");
      return JSON.parse(content);
    } catch {
      return { templates: [] };
    }
  }
  /**
   * Find agents by category
   */
  findAgentsByCategory(index, category) {
    return index.templates.filter((agent) => agent.category === category);
  }
  /**
   * Find skills by category
   */
  findSkillsByCategory(index, category) {
    return index.templates.filter((skill) => skill.category === category);
  }
  /**
   * Find skills by IDs
   */
  findSkillsByIds(index, ids) {
    return index.templates.filter((skill) => ids.includes(skill.id));
  }
  /**
   * Deduplicate and sort templates by priority
   */
  deduplicateAndSort(templates) {
    const seen = /* @__PURE__ */ new Set();
    const unique = [];
    for (const template of templates) {
      if (!seen.has(template.id)) {
        seen.add(template.id);
        unique.push(template);
      }
    }
    return unique.sort((a, b) => b.priority - a.priority);
  }
  /**
   * Generate reasoning for template selection
   */
  generateReasoning(analysis, agents, skills) {
    const reasons = [];
    reasons.push(`Detected ${analysis.projectType} project`);
    if (analysis.frameworks.length > 0) {
      reasons.push(`Using frameworks: ${analysis.frameworks.join(", ")}`);
    }
    reasons.push(`Tech stack: ${analysis.techStack.languages.join(", ")} on ${analysis.techStack.runtime}`);
    if (analysis.hasTests) {
      reasons.push("Tests detected - including test engineer and test generation");
    }
    if (analysis.hasDatabase) {
      reasons.push("Database detected - including migration skills");
    }
    if (analysis.hasApi) {
      reasons.push("API endpoints detected - including API documentation");
    }
    if (analysis.cicd && analysis.cicd.length > 0) {
      reasons.push(`CI/CD detected (${analysis.cicd.join(", ")}) - including DevOps engineer`);
    }
    reasons.push(`
Selected ${agents.length} agents and ${skills.length} skills`);
    return reasons.join("\n");
  }
}
async function selectTemplates(analysis) {
  const selector = new TemplateSelector();
  return selector.select(analysis);
}

async function smartGenerate(projectRoot) {
  const analysis = await analyzeProject(projectRoot);
  const selection = await selectTemplates(analysis);
  const config = await generateConfigs(selection);
  return {
    analysis,
    selection,
    config
  };
}
async function smartGenerateAndInstall(projectRoot) {
  const result = await smartGenerate(projectRoot);
  await writeConfigs(result.config);
  return result;
}

export { ConfigGenerator, ProjectAnalyzer, TemplateSelector, analyzeProject, generateConfigs, selectTemplates, smartGenerate, smartGenerateAndInstall, writeConfigs };
