import { exec } from 'node:child_process';
import { promisify } from 'node:util';
import a from '../chunks/index5.mjs';
import { ensureI18nInitialized, i18n } from '../chunks/index2.mjs';
import { updateCcr } from '../chunks/auto-updater.mjs';
import { w as wrapCommandWithSudo } from '../chunks/platform.mjs';

const execAsync = promisify(exec);
async function isCcrInstalled() {
  let commandExists = false;
  try {
    await execAsync("ccr version");
    commandExists = true;
  } catch {
    try {
      await execAsync("which ccr");
      commandExists = true;
    } catch {
      commandExists = false;
    }
  }
  let hasCorrectPackage = false;
  try {
    await execAsync("npm list -g @musistudio/claude-code-router");
    hasCorrectPackage = true;
  } catch {
    hasCorrectPackage = false;
  }
  return {
    isInstalled: commandExists,
    hasCorrectPackage
  };
}
async function installCcr() {
  ensureI18nInitialized();
  const { isInstalled, hasCorrectPackage } = await isCcrInstalled();
  if (hasCorrectPackage) {
    console.log(a.green(`\u2714 ${i18n.t("ccr:ccrAlreadyInstalled")}`));
    await updateCcr();
    return;
  }
  if (isInstalled && !hasCorrectPackage) {
    try {
      await execAsync("npm list -g claude-code-router");
      console.log(a.yellow(`\u26A0 ${i18n.t("ccr:detectedIncorrectPackage")}`));
      try {
        await execAsync("npm uninstall -g claude-code-router");
        console.log(a.green(`\u2714 ${i18n.t("ccr:uninstalledIncorrectPackage")}`));
      } catch {
        console.log(a.yellow(`\u26A0 ${i18n.t("ccr:failedToUninstallIncorrectPackage")}`));
      }
    } catch {
    }
  }
  console.log(a.green(`\u{1F4E6} ${i18n.t("ccr:installingCcr")}`));
  try {
    const installArgs = ["install", "-g", "@musistudio/claude-code-router", "--force"];
    const { command, args, usedSudo } = wrapCommandWithSudo("npm", installArgs);
    if (usedSudo) {
      console.log(a.yellow(`\u2139 ${i18n.t("installation:usingSudo")}`));
    }
    await execAsync([command, ...args].join(" "));
    console.log(a.green(`\u2714 ${i18n.t("ccr:ccrInstallSuccess")}`));
  } catch (error) {
    if (error.message?.includes("EEXIST")) {
      console.log(a.yellow(`\u26A0 ${i18n.t("ccr:ccrAlreadyInstalled")}`));
      await updateCcr();
      return;
    }
    console.error(a.red(`\u2716 ${i18n.t("ccr:ccrInstallFailed")}`));
    throw error;
  }
}

export { installCcr as a, isCcrInstalled as i };
