import { existsSync } from 'node:fs';
import { rm, mkdir, copyFile } from 'node:fs/promises';
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 { r as resolveClaudeFamilySettingsTarget } from './ccjk.DDL-4C-k.mjs';
import { j as join, d as dirname } from './ccjk.bQ7Dh1g4.mjs';

const WORKFLOW_CONFIG_BASE = [
  {
    id: "interviewWorkflow",
    defaultSelected: true,
    order: 1,
    commands: ["interview.md"],
    agents: [],
    autoInstallAgents: false,
    category: "interview",
    displayCategory: "planning",
    outputDir: "interview",
    metadata: {
      version: "1.0.0",
      addedDate: "2025-01",
      tags: ["recommended", "popular"],
      difficulty: "beginner"
    }
  },
  {
    id: "essentialTools",
    defaultSelected: true,
    order: 2,
    commands: ["init-project.md", "feat.md", "goal.md"],
    agents: [
      { id: "init-architect", filename: "init-architect.md", required: true },
      { id: "get-current-datetime", filename: "get-current-datetime.md", required: true },
      { id: "planner", filename: "planner.md", required: true },
      { id: "ui-ux-designer", filename: "ui-ux-designer.md", required: true }
    ],
    autoInstallAgents: true,
    category: "essential",
    displayCategory: "planning",
    outputDir: "essential",
    metadata: {
      version: "1.0.0",
      addedDate: "2025-01",
      tags: ["essential"],
      difficulty: "beginner"
    }
  },
  {
    id: "gitWorkflow",
    defaultSelected: true,
    order: 3,
    commands: ["git-commit.md", "git-rollback.md", "git-cleanBranches.md", "git-worktree.md"],
    agents: [],
    autoInstallAgents: false,
    category: "git",
    displayCategory: "versionControl",
    outputDir: "git",
    metadata: {
      version: "1.0.0",
      addedDate: "2025-01",
      tags: ["popular"],
      difficulty: "beginner"
    }
  },
  {
    id: "sixStepsWorkflow",
    defaultSelected: false,
    order: 4,
    commands: ["workflow.md"],
    agents: [],
    autoInstallAgents: false,
    category: "sixStep",
    displayCategory: "development",
    outputDir: "workflow",
    metadata: {
      version: "1.0.0",
      addedDate: "2025-01",
      tags: ["professional"],
      difficulty: "intermediate"
    }
  },
  {
    id: "specFirstTDD",
    defaultSelected: false,
    order: 5,
    commands: ["spec-first-tdd.md"],
    agents: [],
    autoInstallAgents: false,
    category: "specFirstTDD",
    displayCategory: "quality",
    outputDir: "spec-first-tdd",
    metadata: {
      version: "1.0.0",
      addedDate: "2025-02",
      tags: ["professional", "new"],
      difficulty: "advanced"
    }
  },
  {
    id: "continuousDelivery",
    defaultSelected: false,
    order: 6,
    commands: ["continuous-delivery.md"],
    agents: [],
    autoInstallAgents: false,
    category: "continuousDelivery",
    displayCategory: "quality",
    outputDir: "continuous-delivery",
    metadata: {
      version: "1.0.0",
      addedDate: "2025-02",
      tags: ["professional", "new"],
      difficulty: "advanced"
    }
  },
  {
    id: "refactoringMaster",
    defaultSelected: false,
    order: 7,
    commands: ["refactoring-master.md"],
    agents: [],
    autoInstallAgents: false,
    category: "refactoringMaster",
    displayCategory: "quality",
    outputDir: "refactoring-master",
    metadata: {
      version: "1.0.0",
      addedDate: "2025-02",
      tags: ["professional", "new"],
      difficulty: "advanced"
    }
  },
  {
    id: "linearMethod",
    defaultSelected: false,
    order: 8,
    commands: ["linear-method.md"],
    agents: [],
    autoInstallAgents: false,
    category: "linearMethod",
    displayCategory: "planning",
    outputDir: "linear-method",
    metadata: {
      version: "1.0.0",
      addedDate: "2025-02",
      tags: ["new"],
      difficulty: "intermediate"
    }
  }
];
function getWorkflowConfigs() {
  ensureI18nInitialized();
  const workflowTranslations = [
    {
      id: "interviewWorkflow",
      name: i18n.t("workflow:workflowOption.interviewWorkflow"),
      description: i18n.t("workflow:workflowDescription.interviewWorkflow"),
      stats: i18n.t("workflow:workflowStats.interviewWorkflow")
    },
    {
      id: "essentialTools",
      name: i18n.t("workflow:workflowOption.essentialTools"),
      description: i18n.t("workflow:workflowDescription.essentialTools"),
      stats: i18n.t("workflow:workflowStats.essentialTools")
    },
    {
      id: "gitWorkflow",
      name: i18n.t("workflow:workflowOption.gitWorkflow"),
      description: i18n.t("workflow:workflowDescription.gitWorkflow"),
      stats: i18n.t("workflow:workflowStats.gitWorkflow")
    },
    {
      id: "sixStepsWorkflow",
      name: i18n.t("workflow:workflowOption.sixStepsWorkflow"),
      description: i18n.t("workflow:workflowDescription.sixStepsWorkflow"),
      stats: i18n.t("workflow:workflowStats.sixStepsWorkflow")
    },
    {
      id: "specFirstTDD",
      name: i18n.t("workflow:workflowOption.specFirstTDD"),
      description: i18n.t("workflow:workflowDescription.specFirstTDD"),
      stats: i18n.t("workflow:workflowStats.specFirstTDD")
    },
    {
      id: "continuousDelivery",
      name: i18n.t("workflow:workflowOption.continuousDelivery"),
      description: i18n.t("workflow:workflowDescription.continuousDelivery"),
      stats: i18n.t("workflow:workflowStats.continuousDelivery")
    },
    {
      id: "refactoringMaster",
      name: i18n.t("workflow:workflowOption.refactoringMaster"),
      description: i18n.t("workflow:workflowDescription.refactoringMaster"),
      stats: i18n.t("workflow:workflowStats.refactoringMaster")
    },
    {
      id: "linearMethod",
      name: i18n.t("workflow:workflowOption.linearMethod"),
      description: i18n.t("workflow:workflowDescription.linearMethod"),
      stats: i18n.t("workflow:workflowStats.linearMethod")
    }
  ];
  return WORKFLOW_CONFIG_BASE.map((baseConfig) => {
    const translation = workflowTranslations.find((t) => t.id === baseConfig.id);
    return {
      ...baseConfig,
      name: translation?.name || baseConfig.id,
      description: translation?.description,
      stats: translation?.stats
    };
  });
}
function getWorkflowConfig(workflowId) {
  return getWorkflowConfigs().find((config) => config.id === workflowId);
}
function getOrderedWorkflows() {
  return getWorkflowConfigs().sort((a, b) => a.order - b.order);
}
function getTagLabel(tag) {
  ensureI18nInitialized();
  const tagKeys = {
    recommended: "workflow:tags.recommended",
    popular: "workflow:tags.popular",
    new: "workflow:tags.new",
    essential: "workflow:tags.essential",
    professional: "workflow:tags.professional"
  };
  return i18n.t(tagKeys[tag]);
}

function getRootDir() {
  const currentFilePath = fileURLToPath(import.meta.url);
  const distDir = dirname(dirname(currentFilePath));
  return dirname(distDir);
}
const DEFAULT_CODE_TOOL_TEMPLATE = "claude-code";
const COMMON_TEMPLATE_CATEGORIES = ["git", "sixStep", "essential", "interview", "specFirstTDD", "continuousDelivery", "refactoringMaster", "linearMethod"];
function formatTags(tags) {
  const tagColors = {
    recommended: (text) => a.bgGreen.black(` ${text} `),
    popular: (text) => a.bgYellow.black(` ${text} `),
    new: (text) => a.bgCyan.black(` ${text} `),
    essential: (text) => a.bgBlue.white(` ${text} `),
    professional: (text) => a.bgMagenta.white(` ${text} `)
  };
  return tags.map((tag) => tagColors[tag](getTagLabel(tag))).join(" ");
}
function buildWorkflowChoice(workflow) {
  const tags = formatTags(workflow.metadata.tags);
  const stats = workflow.stats ? a.dim(workflow.stats) : "";
  const description = workflow.description ? a.gray(workflow.description) : "";
  const nameLine = `${workflow.name} ${tags}`;
  const detailLine = stats ? `     ${stats}` : "";
  const descLine = description ? `     ${description}` : "";
  const displayName = [nameLine, detailLine, descLine].filter(Boolean).join("\n");
  return {
    name: displayName,
    value: workflow.id,
    checked: workflow.defaultSelected
  };
}
async function selectAndInstallWorkflows(configLang, preselectedWorkflows, options = {}) {
  ensureI18nInitialized();
  const workflows = getOrderedWorkflows();
  const choices = workflows.map((workflow) => buildWorkflowChoice(workflow));
  let selectedWorkflows;
  if (preselectedWorkflows) {
    selectedWorkflows = preselectedWorkflows;
  } else {
    console.log("");
    console.log(a.bold.cyan("\u2501".repeat(60)));
    console.log(a.bold.white(`  \u{1F680} ${i18n.t("workflow:selectWorkflowType")}`));
    console.log(a.bold.cyan("\u2501".repeat(60)));
    console.log("");
    const response = await inquirer.prompt({
      type: "checkbox",
      name: "selectedWorkflows",
      message: i18n.t("common:multiSelectHint"),
      choices,
      pageSize: 15
    });
    selectedWorkflows = response.selectedWorkflows;
  }
  if (!selectedWorkflows || selectedWorkflows.length === 0) {
    console.log(a.yellow(i18n.t("common:cancelled")));
    return;
  }
  const installTarget = resolveClaudeFamilySettingsTarget(options.codeToolType);
  await cleanupOldVersionFiles(installTarget.configDir);
  for (const workflowId of selectedWorkflows) {
    const config = getWorkflowConfig(workflowId);
    if (config) {
      await installWorkflowWithDependencies(config, configLang, installTarget.configDir);
    }
  }
}
async function installWorkflowWithDependencies(config, configLang, runtimeConfigDir) {
  const rootDir = getRootDir();
  ensureI18nInitialized();
  const result = {
    workflow: config.id,
    success: true,
    installedCommands: [],
    installedAgents: [],
    errors: []
  };
  const WORKFLOW_OPTION_KEYS = {
    essentialTools: i18n.t("workflow:workflowOption.essentialTools"),
    sixStepsWorkflow: i18n.t("workflow:workflowOption.sixStepsWorkflow"),
    gitWorkflow: i18n.t("workflow:workflowOption.gitWorkflow"),
    interviewWorkflow: i18n.t("workflow:workflowOption.interviewWorkflow"),
    specFirstTDD: i18n.t("workflow:workflowOption.specFirstTDD"),
    continuousDelivery: i18n.t("workflow:workflowOption.continuousDelivery"),
    refactoringMaster: i18n.t("workflow:workflowOption.refactoringMaster"),
    linearMethod: i18n.t("workflow:workflowOption.linearMethod")
  };
  const workflowName = WORKFLOW_OPTION_KEYS[config.id] || config.id;
  console.log(a.green(`
\u{1F4E6} ${i18n.t("workflow:installingWorkflow")}: ${workflowName}...`));
  const commandsDir = join(runtimeConfigDir, "commands", "ccjk");
  if (!existsSync(commandsDir)) {
    await mkdir(commandsDir, { recursive: true });
  }
  for (const commandFile of config.commands) {
    const isCommonTemplate = COMMON_TEMPLATE_CATEGORIES.includes(config.category);
    const commandSource = isCommonTemplate ? join(
      rootDir,
      "templates",
      "common",
      "workflow",
      config.category,
      configLang,
      commandFile
    ) : join(
      rootDir,
      "templates",
      DEFAULT_CODE_TOOL_TEMPLATE,
      configLang,
      "workflow",
      config.category,
      "commands",
      commandFile
    );
    const destFileName = commandFile;
    const commandDest = join(commandsDir, destFileName);
    if (existsSync(commandSource)) {
      try {
        await copyFile(commandSource, commandDest);
        result.installedCommands.push(destFileName);
        console.log(a.gray(`  \u2714 ${i18n.t("workflow:installedCommand")}: ccjk/${destFileName}`));
      } catch (error) {
        const errorMsg = `${i18n.t("workflow:failedToInstallCommand")} ${commandFile}: ${error}`;
        result.errors?.push(errorMsg);
        console.error(a.red(`  \u2717 ${errorMsg}`));
        result.success = false;
      }
    }
  }
  if (config.autoInstallAgents && config.agents.length > 0) {
    const agentsCategoryDir = join(runtimeConfigDir, "agents", "ccjk", config.category);
    if (!existsSync(agentsCategoryDir)) {
      await mkdir(agentsCategoryDir, { recursive: true });
    }
    for (const agent of config.agents) {
      const isCommonTemplate = COMMON_TEMPLATE_CATEGORIES.includes(config.category);
      const agentSource = isCommonTemplate ? join(
        rootDir,
        "templates",
        "common",
        "workflow",
        config.category,
        configLang,
        "agents",
        agent.filename
      ) : join(
        rootDir,
        "templates",
        DEFAULT_CODE_TOOL_TEMPLATE,
        configLang,
        "workflow",
        config.category,
        "agents",
        agent.filename
      );
      const agentDest = join(agentsCategoryDir, agent.filename);
      if (existsSync(agentSource)) {
        try {
          await copyFile(agentSource, agentDest);
          result.installedAgents.push(agent.filename);
          console.log(a.gray(`  \u2714 ${i18n.t("workflow:installedAgent")}: ccjk/${config.category}/${agent.filename}`));
        } catch (error) {
          const errorMsg = `${i18n.t("workflow:failedToInstallAgent")} ${agent.filename}: ${error}`;
          result.errors?.push(errorMsg);
          console.error(a.red(`  \u2717 ${errorMsg}`));
          if (agent.required) {
            result.success = false;
          }
        }
      }
    }
  }
  if (result.success) {
    console.log(a.green(`\u2714 ${workflowName} ${i18n.t("workflow:workflowInstallSuccess")}`));
  } else {
    console.log(a.red(`\u2717 ${workflowName} ${i18n.t("workflow:workflowInstallError")}`));
  }
  return result;
}
async function cleanupOldVersionFiles(runtimeConfigDir) {
  ensureI18nInitialized();
  console.log(a.green(`
\u{1F9F9} ${i18n.t("workflow:cleaningOldFiles")}...`));
  const oldCommandFiles = [
    join(runtimeConfigDir, "commands", "workflow.md"),
    join(runtimeConfigDir, "commands", "feat.md")
  ];
  const oldAgentFiles = [
    join(runtimeConfigDir, "agents", "planner.md"),
    join(runtimeConfigDir, "agents", "ui-ux-designer.md")
  ];
  for (const file of oldCommandFiles) {
    if (existsSync(file)) {
      try {
        await rm(file, { force: true });
        console.log(a.gray(`  \u2714 ${i18n.t("workflow:removedOldFile")}: ${formatRuntimePath(file, runtimeConfigDir)}`));
      } catch {
        console.error(a.yellow(`  \u26A0 ${i18n.t("errors:failedToRemoveFile")}: ${formatRuntimePath(file, runtimeConfigDir)}`));
      }
    }
  }
  for (const file of oldAgentFiles) {
    if (existsSync(file)) {
      try {
        await rm(file, { force: true });
        console.log(a.gray(`  \u2714 ${i18n.t("workflow:removedOldFile")}: ${formatRuntimePath(file, runtimeConfigDir)}`));
      } catch {
        console.error(a.yellow(`  \u26A0 ${i18n.t("errors:failedToRemoveFile")}: ${formatRuntimePath(file, runtimeConfigDir)}`));
      }
    }
  }
}
function formatRuntimePath(filePath, runtimeConfigDir) {
  const homeLabel = runtimeConfigDir.endsWith(".clavue") ? "~/.clavue" : "~/.claude";
  return filePath.replace(runtimeConfigDir, homeLabel);
}

export { WORKFLOW_CONFIG_BASE as W, selectAndInstallWorkflows as s };
