import { fileURLToPath } from 'node:url';
import a from '../chunks/index5.mjs';
import { i as inquirer } from '../chunks/index6.mjs';
import { ensureI18nInitialized, i18n } from '../chunks/index2.mjs';
import { updateZcfConfig } from '../chunks/ccjk-config.mjs';
import { r as resolveClaudeFamilySettingsTarget, n as normalizeClaudeFamilySettings } from './ccjk.DDL-4C-k.mjs';
import { exists, removeFile, ensureDir, copyFile } from '../chunks/fs-operations.mjs';
import { readJsonConfig, writeJsonConfig } from '../chunks/json-config.mjs';
import { m as mergeAndCleanPermissions } from '../chunks/config.mjs';
import { a as addNumbersToChoices } from './ccjk.BFQ7yr5S.mjs';
import { p as promptBoolean } from './ccjk.DZ2LLOa-.mjs';
import { j as join, d as dirname } from './ccjk.bQ7Dh1g4.mjs';

const OUTPUT_STYLES = [
  // Custom styles (have template files) - 大神模式
  {
    id: "linus-mode",
    isCustom: true,
    filePath: "linus-mode.md"
  },
  {
    id: "uncle-bob-mode",
    isCustom: true,
    filePath: "uncle-bob-mode.md"
  },
  {
    id: "dhh-mode",
    isCustom: true,
    filePath: "dhh-mode.md"
  },
  {
    id: "carmack-mode",
    isCustom: true,
    filePath: "carmack-mode.md"
  },
  {
    id: "jobs-mode",
    isCustom: true,
    filePath: "jobs-mode.md"
  },
  {
    id: "evan-you-mode",
    isCustom: true,
    filePath: "evan-you-mode.md"
  },
  {
    id: "codex-rigor-mode",
    isCustom: true,
    filePath: "codex-rigor-mode.md"
  },
  // Built-in styles (no template files) - Claude Code native styles
  {
    id: "default",
    isCustom: false
  },
  {
    id: "explanatory",
    isCustom: false
  },
  {
    id: "learning",
    isCustom: false
  }
];
const LEGACY_FILES = ["personality.md", "rules.md", "technical-guides.md", "mcp.md", "language.md"];
function getAvailableOutputStyles() {
  return OUTPUT_STYLES;
}
async function copyOutputStyles(selectedStyles, lang, codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const outputStylesDir = join(target.configDir, "output-styles");
  ensureDir(outputStylesDir);
  const currentFilePath = fileURLToPath(import.meta.url);
  const distDir = dirname(dirname(currentFilePath));
  const rootDir = dirname(distDir);
  const templateDir = join(rootDir, "templates", "common", "output-styles", lang);
  for (const styleId of selectedStyles) {
    const style = OUTPUT_STYLES.find((s) => s.id === styleId);
    if (!style || !style.isCustom || !style.filePath) {
      continue;
    }
    const sourcePath = join(templateDir, style.filePath);
    const destPath = join(outputStylesDir, style.filePath);
    if (exists(sourcePath)) {
      copyFile(sourcePath, destPath);
    }
  }
}
const BUILTIN_STYLE_IDS = /* @__PURE__ */ new Set(["default", "explanatory", "learning"]);
function setGlobalDefaultOutputStyle(styleId, codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  if (BUILTIN_STYLE_IDS.has(styleId)) {
    console.log(a.yellow(`\u26A0\uFE0F  Note: Built-in output styles (${styleId}) are deprecated in Claude Code 2.1+.`));
    console.log(a.gray("   Custom styles (linus-mode, etc.) stored as .md files are still fully supported."));
  }
  const templatePermissions = getTemplatePermissions();
  const existingSettings = readJsonConfig(target.settingsFile) || {};
  const cleanedPermissions = mergeAndCleanPermissions(
    templatePermissions,
    existingSettings.permissions?.allow
  );
  const updatedSettings = {
    ...existingSettings,
    outputStyle: styleId,
    // Ensure clean permissions without dropping trusted-operator mode fields.
    permissions: {
      ...existingSettings.permissions || {},
      allow: cleanedPermissions
    }
  };
  if (updatedSettings.plansDirectory === null) {
    delete updatedSettings.plansDirectory;
  }
  normalizeClaudeFamilySettings(updatedSettings);
  writeJsonConfig(target.settingsFile, updatedSettings);
}
function getTemplatePermissions() {
  try {
    const { readFileSync } = require("node:fs");
    const { fileURLToPath: fileURLToPath2 } = require("node:url");
    const { dirname: dirname2, join: join2 } = require("pathe");
    const currentFilePath = fileURLToPath2(import.meta.url);
    const distDir = dirname2(dirname2(currentFilePath));
    const rootDir = dirname2(distDir);
    const templatePath = join2(rootDir, "templates", "claude-code", "common", "settings.json");
    if (require("node:fs").existsSync(templatePath)) {
      const template = JSON.parse(readFileSync(templatePath, "utf-8"));
      return template.permissions?.allow || [];
    }
  } catch (_error) {
  }
  return [
    "Bash(git *)",
    "Bash(npm *)",
    "Bash(pnpm *)",
    "Bash(node *)",
    "Read(*)",
    "Edit(*)",
    "Write(*)"
  ];
}
function hasLegacyPersonalityFiles(codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  return LEGACY_FILES.some((filename) => exists(join(target.configDir, filename)));
}
function cleanupLegacyPersonalityFiles(codeTool) {
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  LEGACY_FILES.forEach((filename) => {
    const filePath = join(target.configDir, filename);
    if (exists(filePath)) {
      removeFile(filePath);
    }
  });
}
async function configureOutputStyle(preselectedStyles, preselectedDefault, codeTool) {
  ensureI18nInitialized();
  const outputStyleList = [
    {
      id: "default",
      name: i18n.t("configuration:outputStyles.default.name"),
      description: i18n.t("configuration:outputStyles.default.description")
    },
    {
      id: "linus-mode",
      name: i18n.t("configuration:outputStyles.linus-mode.name"),
      description: i18n.t("configuration:outputStyles.linus-mode.description")
    },
    {
      id: "uncle-bob-mode",
      name: i18n.t("configuration:outputStyles.uncle-bob-mode.name"),
      description: i18n.t("configuration:outputStyles.uncle-bob-mode.description")
    },
    {
      id: "dhh-mode",
      name: i18n.t("configuration:outputStyles.dhh-mode.name"),
      description: i18n.t("configuration:outputStyles.dhh-mode.description")
    },
    {
      id: "carmack-mode",
      name: i18n.t("configuration:outputStyles.carmack-mode.name"),
      description: i18n.t("configuration:outputStyles.carmack-mode.description")
    },
    {
      id: "jobs-mode",
      name: i18n.t("configuration:outputStyles.jobs-mode.name"),
      description: i18n.t("configuration:outputStyles.jobs-mode.description")
    },
    {
      id: "evan-you-mode",
      name: i18n.t("configuration:outputStyles.evan-you-mode.name"),
      description: i18n.t("configuration:outputStyles.evan-you-mode.description")
    },
    {
      id: "codex-rigor-mode",
      name: i18n.t("configuration:outputStyles.codex-rigor-mode.name"),
      description: i18n.t("configuration:outputStyles.codex-rigor-mode.description")
    },
    {
      id: "explanatory",
      name: i18n.t("configuration:outputStyles.explanatory.name"),
      description: i18n.t("configuration:outputStyles.explanatory.description")
    },
    {
      id: "learning",
      name: i18n.t("configuration:outputStyles.learning.name"),
      description: i18n.t("configuration:outputStyles.learning.description")
    }
  ];
  const availableStyles = getAvailableOutputStyles();
  if (hasLegacyPersonalityFiles(codeTool) && !preselectedStyles) {
    console.log(a.yellow(`\u26A0\uFE0F  ${i18n.t("configuration:legacyFilesDetected")}`));
    const cleanupLegacy = await promptBoolean({
      message: i18n.t("configuration:cleanupLegacyFiles"),
      defaultValue: true
    });
    if (cleanupLegacy) {
      cleanupLegacyPersonalityFiles(codeTool);
      console.log(a.green(`\u2714 ${i18n.t("configuration:legacyFilesRemoved")}`));
    }
  } else if (hasLegacyPersonalityFiles(codeTool) && preselectedStyles) {
    cleanupLegacyPersonalityFiles(codeTool);
  }
  let selectedStyles;
  let defaultStyle;
  if (preselectedStyles && preselectedDefault) {
    selectedStyles = preselectedStyles;
    defaultStyle = preselectedDefault;
  } else {
    const customStyles = availableStyles.filter((style) => style.isCustom);
    const { selectedStyles: promptedStyles } = await inquirer.prompt({
      type: "checkbox",
      name: "selectedStyles",
      message: `${i18n.t("configuration:selectOutputStyles")}${i18n.t("common:multiSelectHint")}`,
      choices: addNumbersToChoices(customStyles.map((style) => {
        const styleInfo = outputStyleList.find((s) => s.id === style.id);
        return {
          name: `${styleInfo?.name || style.id} - ${a.gray(styleInfo?.description || "")}`,
          value: style.id,
          checked: true
          // Default to all selected
        };
      })),
      validate: async (input) => input.length > 0 || i18n.t("configuration:selectAtLeastOne")
    });
    if (!promptedStyles || promptedStyles.length === 0) {
      console.log(a.yellow(i18n.t("common:cancelled")));
      return;
    }
    selectedStyles = promptedStyles;
    const { defaultStyle: promptedDefault } = await inquirer.prompt({
      type: "list",
      name: "defaultStyle",
      message: i18n.t("configuration:selectDefaultOutputStyle"),
      choices: addNumbersToChoices([
        // Show selected custom styles first (only what user actually installed)
        ...selectedStyles.map((styleId) => {
          const styleInfo = outputStyleList.find((s) => s.id === styleId);
          return {
            name: `${styleInfo?.name || styleId} - ${a.gray(styleInfo?.description || "")}`,
            value: styleId,
            short: styleInfo?.name || styleId
          };
        }),
        // Then show all built-in styles (always available)
        ...availableStyles.filter((style) => !style.isCustom).map((style) => {
          const styleInfo = outputStyleList.find((s) => s.id === style.id);
          return {
            name: `${styleInfo?.name || style.id} - ${a.gray(styleInfo?.description || "")}`,
            value: style.id,
            short: styleInfo?.name || style.id
          };
        })
      ]),
      default: selectedStyles.includes("linus-mode") ? "linus-mode" : selectedStyles[0]
    });
    if (!promptedDefault) {
      console.log(a.yellow(i18n.t("common:cancelled")));
      return;
    }
    defaultStyle = promptedDefault;
  }
  await copyOutputStyles(selectedStyles, "zh-CN", codeTool);
  setGlobalDefaultOutputStyle(defaultStyle, codeTool);
  updateZcfConfig({
    outputStyles: selectedStyles,
    defaultOutputStyle: defaultStyle
  });
  console.log(a.green(`\u2714 ${i18n.t("configuration:outputStyleInstalled")}`));
  console.log(a.gray(`  ${i18n.t("configuration:selectedStyles")}: ${selectedStyles.join(", ")}`));
  console.log(a.gray(`  ${i18n.t("configuration:defaultStyle")}: ${defaultStyle}`));
}

export { configureOutputStyle as a, copyOutputStyles as c, getAvailableOutputStyles as g, setGlobalDefaultOutputStyle as s };
