import { promises } from 'node:fs';
import { homedir } from 'node:os';
import { join, dirname } from 'node:path';
import { fileURLToPath } from 'node:url';
import a from './index5.mjs';
import { c as consola, a as analyzeProject, g as getTemplatesClient } from '../shared/ccjk.CoCHVXl3.mjs';
import { i as inquirer } from './index6.mjs';
import { resolveSupportedLanguage, i18n } from './index2.mjs';
import { g as getSkillParser } from '../shared/ccjk.i_vn-9C3.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import './index10.mjs';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import 'tinyglobby';
import '../shared/ccjk.BBtCGd_g.mjs';
import './constants.mjs';
import 'node:process';
import 'node:readline';
import 'stream';
import 'node:tty';
import 'node:async_hooks';
import '../shared/ccjk.Cjgrln_h.mjs';
import 'node:util';
import 'tty';
import 'fs';
import 'child_process';
import 'node:crypto';
import 'buffer';
import 'string_decoder';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
async function ccjkSkills(options = {}) {
  const logger = consola.withTag("ccjk:skills");
  const startTime = Date.now();
  try {
    const lang = resolveSupportedLanguage(options.lang);
    if (lang !== i18n.language) {
      await i18n.changeLanguage(lang);
    }
    const opts = {
      lang,
      interactive: options.interactive ?? true,
      category: options.category || "",
      tags: options.tags || [],
      exclude: options.exclude || [],
      dryRun: options.dryRun ?? false,
      json: options.json ?? false,
      force: options.force ?? false,
      targetDir: options.targetDir || process.cwd()
    };
    if (opts.json) {
      console.log(JSON.stringify({ status: "starting", options: opts }));
    }
    if (!opts.json) {
      console.log("");
      console.log(a.bold.cyan("\u2501".repeat(60)));
      console.log(a.bold.cyan(`  ${i18n.t("ccjk-skills:title")}`));
      console.log(a.bold.cyan("\u2501".repeat(60)));
      console.log("");
    }
    if (!opts.json) {
      console.log(a.bold(`  ${i18n.t("ccjk-skills:analyzing")}`));
    }
    const analysis = await analyzeProject(opts.targetDir, {
      analyzeTransitiveDeps: true
      // Don't override maxFilesToScan - use default of 10000
    });
    if (!opts.json) {
      displayProjectInfo(analysis, opts.lang);
    }
    if (!opts.json) {
      console.log("");
      console.log(a.bold(`  ${i18n.t("ccjk-skills:recommending")}`));
    }
    const recommendedSkills = await getRecommendedSkills(analysis, opts);
    if (recommendedSkills.length === 0) {
      if (!opts.json) {
        console.log(a.yellow(`  ${i18n.t("ccjk-skills:noSkillsFound")}`));
        console.log("");
        console.log(a.dim(`  ${i18n.t("ccjk-skills:tryDifferentProject")}`));
      } else {
        console.log(JSON.stringify({
          status: "completed",
          skillsFound: 0,
          skillsInstalled: 0,
          duration: Date.now() - startTime
        }));
      }
      return;
    }
    const selectedSkills = await selectSkills(recommendedSkills, opts);
    if (selectedSkills.length === 0) {
      if (!opts.json) {
        console.log(a.yellow(`  ${i18n.t("ccjk-skills:noSkillsSelected")}`));
      } else {
        console.log(JSON.stringify({
          status: "completed",
          skillsFound: recommendedSkills.length,
          skillsSelected: 0,
          duration: Date.now() - startTime
        }));
      }
      return;
    }
    if (!opts.json) {
      console.log("");
      console.log(a.bold(`  ${i18n.t("ccjk-skills:installing")}`));
    }
    const results = await installSkills(selectedSkills, opts);
    const successful = results.filter((r) => r.success);
    const failed = results.filter((r) => !r.success);
    if (!opts.json) {
      displayInstallationResults(results, opts.lang);
      if (successful.length > 0) {
        console.log("");
        console.log(a.bold(a.green(`  \u2713 ${i18n.t("ccjk-skills:installedCount", { count: successful.length })}`)));
        console.log("");
        console.log(a.bold(`  ${i18n.t("ccjk-skills:nextSteps")}:`));
        console.log(a.dim(`    \u2022 ${i18n.t("ccjk-skills:useMcpCommand")}`));
        console.log(a.dim(`    \u2022 ${i18n.t("ccjk-skills:useAgentsCommand")}`));
        console.log(a.dim(`    \u2022 ${i18n.t("ccjk-skills:useSetupCommand")}`));
      }
    } else {
      console.log(JSON.stringify({
        status: "completed",
        skillsFound: recommendedSkills.length,
        skillsSelected: selectedSkills.length,
        skillsInstalled: successful.length,
        skillsFailed: failed.length,
        results,
        duration: Date.now() - startTime
      }));
    }
    logger.success(`Completed in ${Date.now() - startTime}ms`);
  } catch (error) {
    logger.error("Failed to install skills:", error);
    if (options.json) {
      console.log(JSON.stringify({
        status: "error",
        error: error instanceof Error ? error.message : String(error)
      }));
    } else {
      console.error(a.red(`
  ${i18n.t("ccjk-skills:error")}: ${error instanceof Error ? error.message : String(error)}`));
    }
    throw error;
  }
}
function displayProjectInfo(analysis, _lang) {
  const pm = analysis.packageManager || "unknown";
  const frameworks = analysis.frameworks.map((f) => f.name).join(", ");
  const languages = analysis.languages.filter((l) => l.confidence > 0.5).map((l) => l.language).join(", ");
  console.log(a.dim(`    ${i18n.t("ccjk-skills:detected")}: ${languages}`));
  if (frameworks) {
    console.log(a.dim(`    ${i18n.t("ccjk-skills:frameworks")}: ${frameworks}`));
  }
  console.log(a.dim(`    ${i18n.t("ccjk-skills:packageManager")}: ${pm}`));
  if (analysis.buildSystem) {
    console.log(a.dim(`    ${i18n.t("ccjk-skills:buildSystem")}: ${analysis.buildSystem}`));
  }
}
async function getRecommendedSkills(analysis, options) {
  const logger = consola.withTag("recommender");
  const recommendations = [];
  const isZh = options.lang === "zh-CN";
  const languages = analysis.languages.map((l) => l.language.toLowerCase());
  const frameworks = analysis.frameworks.map((f) => f.name.toLowerCase());
  const projectType = analysis.projectType?.toLowerCase() || "";
  const localSkills = await getLocalRecommendations(analysis);
  recommendations.push(...localSkills);
  try {
    const templatesClient = getTemplatesClient({ language: isZh ? "zh-CN" : "en" });
    logger.info("Fetching cloud recommendations...");
    const cloudSkills = await Promise.race([
      templatesClient.getSkills(),
      new Promise((_, reject) => setTimeout(() => reject(new Error("timeout")), 3e3))
    ]);
    if (cloudSkills.length > 0) {
      logger.success(isZh ? `\u4ECE\u4E91\u7AEF\u83B7\u53D6 ${cloudSkills.length} \u4E2A\u6280\u80FD` : `Fetched ${cloudSkills.length} skills from cloud`);
      const localSkillIds = new Set(recommendations.map((s) => s.id));
      const relevantSkills = cloudSkills.filter((skill) => {
        const tags = skill.tags || [];
        const _category = skill.category || "";
        const compatibility = skill.compatibility || {};
        return tags.some((tag) => languages.includes(tag) || frameworks.includes(tag) || projectType.includes(tag)) || (compatibility.languages || []).some((lang) => languages.includes(lang.toLowerCase())) || (compatibility.frameworks || []).some((fw) => frameworks.includes(fw.toLowerCase()));
      });
      for (const skill of relevantSkills.length > 0 ? relevantSkills : cloudSkills.slice(0, 10)) {
        const skillId = skill.id || skill.name_en.toLowerCase().replace(/\s+/g, "-");
        if (localSkillIds.has(skillId)) {
          continue;
        }
        recommendations.push({
          id: skillId,
          name: {
            "en": skill.name_en,
            "zh-CN": skill.name_zh_cn || skill.name_en
          },
          description: {
            "en": skill.description_en || "",
            "zh-CN": skill.description_zh_cn || skill.description_en || ""
          },
          category: skill.category || "custom",
          priority: skill.rating_average ? skill.rating_average * 2 : 7,
          source: "cloud",
          tags: skill.tags || [],
          templatePath: skillId,
          // Store template content from V8 API response
          templateContent: skill.template_content || skill.content
        });
      }
    }
  } catch {
    logger.debug("Cloud recommendations unavailable, using local templates only");
  }
  const seen = /* @__PURE__ */ new Set();
  const unique = [];
  for (const skill of recommendations) {
    if (!seen.has(skill.id)) {
      seen.add(skill.id);
      unique.push(skill);
    }
  }
  let filtered = unique;
  if (options.category) {
    filtered = filtered.filter((s) => s.category === options.category);
  }
  if (options.tags.length > 0) {
    filtered = filtered.filter(
      (s) => options.tags.some((tag) => s.tags.includes(tag))
    );
  }
  if (options.exclude.length > 0) {
    filtered = filtered.filter(
      (s) => !options.exclude.includes(s.id)
    );
  }
  filtered.sort((a, b) => b.priority - a.priority);
  return filtered;
}
async function getLocalRecommendations(analysis, _options) {
  const skills = [];
  const langMap = analysis.languages.reduce((acc, l) => {
    acc[l.language] = l.confidence;
    return acc;
  }, {});
  const fwMap = analysis.frameworks.reduce((acc, f) => {
    acc[f.name.toLowerCase()] = f.confidence;
    return acc;
  }, {});
  if (langMap.typescript > 0.5) {
    skills.push({
      id: "ts-best-practices",
      name: { "en": "TypeScript Best Practices", "zh-CN": "TypeScript \u6700\u4F73\u5B9E\u8DF5" },
      description: {
        "en": "TypeScript 5.3+ best practices and patterns for type-safe development",
        "zh-CN": "TypeScript 5.3+ \u6700\u4F73\u5B9E\u8DF5\u548C\u7C7B\u578B\u5B89\u5168\u5F00\u53D1\u6A21\u5F0F"
      },
      category: "dev",
      priority: 8,
      source: "local",
      tags: ["typescript", "types", "patterns"],
      templatePath: "ts-best-practices.md"
    });
  }
  if (fwMap.react > 0.5) {
    skills.push({
      id: "react-patterns",
      name: { "en": "React Patterns", "zh-CN": "React \u8BBE\u8BA1\u6A21\u5F0F" },
      description: {
        "en": "React component design patterns and optimization techniques",
        "zh-CN": "React \u7EC4\u4EF6\u8BBE\u8BA1\u6A21\u5F0F\u548C\u4F18\u5316\u6280\u5DE7"
      },
      category: "dev",
      priority: 7,
      source: "local",
      tags: ["react", "frontend", "patterns"],
      templatePath: "react-patterns.md"
    });
  }
  if ((fwMap["next.js"] || fwMap.next) > 0.5) {
    skills.push({
      id: "nextjs-optimization",
      name: { "en": "Next.js Optimization", "zh-CN": "Next.js \u6027\u80FD\u4F18\u5316" },
      description: {
        "en": "Next.js performance optimization and best practices",
        "zh-CN": "Next.js \u6027\u80FD\u4F18\u5316\u548C\u6700\u4F73\u5B9E\u8DF5"
      },
      category: "dev",
      priority: 7,
      source: "local",
      tags: ["nextjs", "performance", "optimization"],
      templatePath: "nextjs-optimization.md"
    });
  }
  if (langMap.python > 0.5) {
    skills.push({
      id: "python-pep8",
      name: { "en": "Python PEP 8", "zh-CN": "Python PEP 8" },
      description: {
        "en": "Python coding standards and best practices following PEP 8",
        "zh-CN": "\u9075\u5FAA PEP 8 \u7684 Python \u7F16\u7801\u6807\u51C6\u548C\u6700\u4F73\u5B9E\u8DF5"
      },
      category: "dev",
      priority: 7,
      source: "local",
      tags: ["python", "pep8", "standards"],
      templatePath: "python-pep8.md"
    });
  }
  if (analysis.configFiles.some((f) => f.includes("test"))) {
    skills.push({
      id: "testing-best-practices",
      name: { "en": "Testing Best Practices", "zh-CN": "\u6D4B\u8BD5\u6700\u4F73\u5B9E\u8DF5" },
      description: {
        "en": "Testing-driven development workflows and best practices",
        "zh-CN": "\u6D4B\u8BD5\u9A71\u52A8\u5F00\u53D1\u5DE5\u4F5C\u6D41\u548C\u6700\u4F73\u5B9E\u8DF5"
      },
      category: "testing",
      priority: 6,
      source: "local",
      tags: ["testing", "tdd", "quality"],
      templatePath: "testing-best-practices.md"
    });
  }
  if (analysis.configFiles.includes(".git")) {
    skills.push({
      id: "git-workflow",
      name: { "en": "Git Workflow", "zh-CN": "Git \u5DE5\u4F5C\u6D41" },
      description: {
        "en": "Git branch management strategies and best practices",
        "zh-CN": "Git \u5206\u652F\u7BA1\u7406\u7B56\u7565\u548C\u6700\u4F73\u5B9E\u8DF5"
      },
      category: "git",
      priority: 5,
      source: "local",
      tags: ["git", "workflow", "vcs"],
      templatePath: "git-workflow.md"
    });
  }
  return skills;
}
async function selectSkills(recommendations, options) {
  if (!options.interactive) {
    return recommendations.filter((s) => s.priority >= 5);
  }
  console.log("");
  console.log(a.bold(a.cyan(`  ${i18n.t("ccjk-skills:recommendedSkills", { count: recommendations.length })}`)));
  console.log("");
  const choices = recommendations.map((skill) => ({
    name: `${getCategoryIcon(skill.category)} ${skill.name[options.lang]} ${a.dim(`(${skill.category})`)}`,
    value: skill,
    checked: skill.priority >= 7
    // Auto-check high priority skills
  }));
  const { selected } = await inquirer.prompt([
    {
      type: "checkbox",
      name: "selected",
      message: i18n.t("ccjk-skills:selectSkills"),
      choices,
      pageSize: 10
    }
  ]);
  return selected;
}
async function installSkills(skills, options) {
  const results = [];
  const skillsDir = join(process.env.HOME || homedir(), ".claude", "skills");
  const parser = getSkillParser();
  if (!await fileExists(skillsDir)) {
    await promises.mkdir(skillsDir, { recursive: true });
  }
  for (const skill of skills) {
    try {
      if (!options.json) {
        process.stdout.write(`   ${a.dim("\u2192")} ${skill.name[options.lang]}... `);
      }
      if (options.dryRun) {
        if (!options.json) {
          console.log(a.yellow("DRY RUN"));
        }
        results.push({
          skillId: skill.id,
          success: true,
          path: join(skillsDir, skill.id, "SKILL.md")
        });
        continue;
      }
      const templateContent = await loadSkillTemplate(skill);
      if (!templateContent) {
        throw new Error(`Template not found: ${skill.templatePath}`);
      }
      const skillDir = join(skillsDir, skill.id);
      if (!await fileExists(skillDir)) {
        await promises.mkdir(skillDir, { recursive: true });
      }
      const skillMdPath = join(skillDir, "SKILL.md");
      const skillMdContent = generateSkillMdFromTemplate(skill, templateContent);
      await promises.writeFile(skillMdPath, skillMdContent, "utf-8");
      try {
        const parsed = parser.parse(skillMdPath);
        if (!parsed.title || !parsed.description) {
          throw new Error("Invalid SKILL.md format");
        }
      } catch (error) {
        throw new Error(`Generated SKILL.md is invalid: ${error instanceof Error ? error.message : String(error)}`);
      }
      if (!options.json) {
        console.log(a.green("\u2713"));
      }
      results.push({
        skillId: skill.id,
        success: true,
        path: skillMdPath
      });
    } catch (error) {
      if (!options.json) {
        console.log(a.red("\u2717"));
        if (!(error instanceof Error && error.message.includes("DRY RUN"))) {
          console.log(a.red(`     ${error instanceof Error ? error.message : String(error)}`));
        }
      }
      results.push({
        skillId: skill.id,
        success: false,
        error: error instanceof Error ? error.message : String(error)
      });
    }
  }
  return results;
}
async function loadSkillTemplate(skill) {
  const templatePath = skill.templatePath;
  try {
    if (skill.templateContent) {
      return skill.templateContent;
    }
    const isSkillRecord = templatePath.startsWith("skill_");
    if (isSkillRecord) {
      consola.warn(`Cloud skill ${templatePath} has no template content. The cloud API may not have returned the content.`);
      return null;
    }
    const isTemplateId = templatePath.startsWith("tpl_");
    if (isTemplateId) {
      try {
        const templatesClient = getTemplatesClient();
        const template = await templatesClient.getTemplate(templatePath);
        if (template) {
          const content = template.template_content || template.content;
          if (content) {
            return content;
          }
        }
      } catch (error) {
        consola.warn(`Failed to fetch cloud template ${templatePath}:`, error);
      }
    }
    const localPath = join(process.cwd(), "templates", "skills", templatePath);
    if (await fileExists(localPath)) {
      return await promises.readFile(localPath, "utf-8");
    }
    const packagePath = join(__dirname, "..", "..", "templates", "skills", templatePath);
    if (await fileExists(packagePath)) {
      return await promises.readFile(packagePath, "utf-8");
    }
    return null;
  } catch {
    return null;
  }
}
function generateSkillMdFromTemplate(skill, templateContent) {
  return templateContent;
}
function displayInstallationResults(results, _lang) {
  console.log("");
  const successful = results.filter((r) => r.success);
  const failed = results.filter((r) => !r.success);
  if (successful.length > 0) {
    console.log(a.bold(a.green(`  \u2713 ${i18n.t("ccjk-skills:installedCount", { count: successful.length })}`)));
    for (const result of successful) {
      if (result.path) {
        console.log(a.dim(`    ${result.path}`));
      }
    }
  }
  if (failed.length > 0) {
    console.log("");
    console.log(a.bold(a.red(`  \u2717 ${i18n.t("ccjk-skills:failedCount", { count: failed.length })}`)));
    for (const result of failed) {
      console.log(a.red(`    ${result.skillId}: ${result.error}`));
    }
  }
}
async function fileExists(path) {
  try {
    await promises.access(path);
    return true;
  } catch {
    return false;
  }
}
function getCategoryIcon(category) {
  const icons = {
    git: "\u{1F500}",
    dev: "\u{1F4BB}",
    testing: "\u{1F9EA}",
    docs: "\u{1F4DA}",
    review: "\u{1F440}",
    seo: "\u{1F50D}",
    devops: "\u{1F680}",
    planning: "\u{1F4CB}",
    debug: "\u{1F41B}",
    custom: "\u2699\uFE0F"
  };
  return icons[category] || "\u{1F4E6}";
}

export { ccjkSkills };
