import a from './index5.mjs';
import ora from './index8.mjs';
import { exec as q } from './main.mjs';
import { ensureI18nInitialized, i18n, format } from './index2.mjs';
import { s as shouldUseSudoForGlobalInstall } from './platform.mjs';
import { p as promptBoolean } from '../shared/ccjk.DZ2LLOa-.mjs';
import { checkClaudeCodeVersion, fixBrokenNpmSymlink, checkCcrVersion, handleDuplicateInstallations, checkCometixLineVersion, checkMyclaudeVersion } from './version-checker.mjs';
import '../shared/ccjk.BAGoDD49.mjs';
import 'node:process';
import '../shared/ccjk.Cjgrln_h.mjs';
import '../shared/ccjk.DeWpAShp.mjs';
import 'module';
import 'node:child_process';
import 'node:path';
import 'node:stream';
import 'node:readline';
import 'node:fs';
import 'node:url';
import '../shared/ccjk.bQ7Dh1g4.mjs';
import 'node:os';
import 'node:async_hooks';
import './index6.mjs';
import 'stream';
import 'node:tty';
import 'node:util';
import 'tty';
import 'fs';
import 'child_process';
import 'node:crypto';
import 'buffer';
import 'string_decoder';
import '../shared/ccjk.CxpGa6MC.mjs';

async function execWithSudoIfNeeded(command, args) {
  const needsSudo = shouldUseSudoForGlobalInstall();
  if (needsSudo) {
    console.log(a.yellow(`
${i18n.t("updater:usingSudo")}`));
    const result = await q("sudo", [command, ...args]);
    if (result.exitCode !== 0) {
      throw new Error(result.stderr || `Command failed with exit code ${result.exitCode}`);
    }
    return { usedSudo: true };
  } else {
    const result = await q(command, args);
    if (result.exitCode !== 0) {
      throw new Error(result.stderr || `Command failed with exit code ${result.exitCode}`);
    }
    return { usedSudo: false };
  }
}
async function updateCcr(force = false, skipPrompt = false) {
  ensureI18nInitialized();
  const spinner = ora(i18n.t("updater:checkingVersion")).start();
  try {
    const { installed, currentVersion, latestVersion, needsUpdate } = await checkCcrVersion();
    spinner.stop();
    if (!installed) {
      console.log(a.yellow(i18n.t("updater:ccrNotInstalled")));
      return false;
    }
    if (!needsUpdate && !force) {
      console.log(a.green(format(i18n.t("updater:ccrUpToDate"), { version: currentVersion || "" })));
      return true;
    }
    if (!latestVersion) {
      console.log(a.yellow(i18n.t("updater:cannotCheckVersion")));
      return false;
    }
    console.log(a.green(format(i18n.t("updater:currentVersion"), { version: currentVersion || "" })));
    console.log(a.green(format(i18n.t("updater:latestVersion"), { version: latestVersion })));
    if (!skipPrompt) {
      const confirm = await promptBoolean({
        message: format(i18n.t("updater:confirmUpdate"), { tool: "CCR" }),
        defaultValue: true
      });
      if (!confirm) {
        console.log(a.gray(i18n.t("updater:updateSkipped")));
        return true;
      }
    } else {
      console.log(a.green(format(i18n.t("updater:autoUpdating"), { tool: "CCR" })));
    }
    const updateSpinner = ora(format(i18n.t("updater:updating"), { tool: "CCR" })).start();
    try {
      await execWithSudoIfNeeded("npm", ["update", "-g", "@musistudio/claude-code-router"]);
      updateSpinner.succeed(format(i18n.t("updater:updateSuccess"), { tool: "CCR" }));
      return true;
    } catch (error) {
      updateSpinner.fail(format(i18n.t("updater:updateFailed"), { tool: "CCR" }));
      console.error(a.red(error instanceof Error ? error.message : String(error)));
      return false;
    }
  } catch (error) {
    spinner.fail(i18n.t("updater:checkFailed"));
    console.error(a.red(error instanceof Error ? error.message : String(error)));
    return false;
  }
}
async function updateClaudeCode(force = false, skipPrompt = false) {
  ensureI18nInitialized();
  const spinner = ora(i18n.t("updater:checkingVersion")).start();
  try {
    const { installed, currentVersion, latestVersion, needsUpdate, isHomebrew, installationSource, isBroken, hasWrongPackage, wrongPackageName } = await checkClaudeCodeVersion();
    spinner.stop();
    if (hasWrongPackage && wrongPackageName) {
      console.log(a.yellow(`
\u26A0\uFE0F  ${i18n.t("installation:wrongPackageDetected")}`));
      console.log(a.red(`   ${i18n.t("installation:installedPackage")}: ${wrongPackageName}`));
      console.log(a.green(`   ${i18n.t("installation:correctPackage")}: @anthropic-ai/claude-code`));
      console.log();
      if (!skipPrompt) {
        const inquirer = (await import('./index6.mjs').then(function (n) { return n.c; })).default;
        const { shouldFix } = await inquirer.prompt([
          {
            type: "confirm",
            name: "shouldFix",
            message: i18n.t("installation:confirmFixWrongPackage"),
            default: true
          }
        ]);
        if (!shouldFix) {
          console.log(a.gray(i18n.t("installation:wrongPackageSkipped")));
          return false;
        }
      }
      const fixSpinner = ora(i18n.t("installation:fixingWrongPackage")).start();
      try {
        await execWithSudoIfNeeded("npm", ["uninstall", "-g", wrongPackageName]);
        fixSpinner.text = i18n.t("installation:installingCorrectPackage");
        await execWithSudoIfNeeded("npm", ["install", "-g", "@anthropic-ai/claude-code", "--force"]);
        fixSpinner.succeed(a.green(`\u2713 ${i18n.t("installation:wrongPackageFixed")}`));
        console.log(a.green(`
\u2713 ${i18n.t("installation:nowUsingCorrectPackage")}`));
        return true;
      } catch (error) {
        fixSpinner.fail(a.red(`\u2717 ${i18n.t("installation:wrongPackageFixFailed")}`));
        console.error(a.red(error instanceof Error ? error.message : String(error)));
        console.log(a.gray(`
${i18n.t("installation:manualFixHint")}:`));
        console.log(a.gray(`  npm uninstall -g ${wrongPackageName}`));
        console.log(a.gray(`  npm install -g @anthropic-ai/claude-code`));
        return false;
      }
    }
    if (!installed) {
      console.log(a.yellow(i18n.t("updater:claudeCodeNotInstalled")));
      return false;
    }
    if (!needsUpdate && !force) {
      console.log(a.green(format(i18n.t("updater:claudeCodeUpToDate"), { version: currentVersion || "" })));
      return true;
    }
    if (!latestVersion) {
      console.log(a.yellow(i18n.t("updater:cannotCheckVersion")));
      return false;
    }
    console.log(a.green(format(i18n.t("updater:currentVersion"), { version: currentVersion || "" })));
    console.log(a.green(format(i18n.t("updater:latestVersion"), { version: latestVersion })));
    if (isBroken) {
      console.log(a.yellow(i18n.t("updater:installationBroken")));
      const fixResult = await fixBrokenNpmSymlink();
      if (fixResult.fixed) {
        console.log(a.green(`\u2714 ${i18n.t("updater:symlinkFixed")}: ${fixResult.message}`));
        const recheckResult = await checkClaudeCodeVersion();
        if (!recheckResult.isBroken) {
          console.log(a.green(i18n.t("updater:installationRepaired")));
          if (!recheckResult.needsUpdate && !force) {
            console.log(a.green(format(i18n.t("updater:claudeCodeUpToDate"), { version: recheckResult.currentVersion || "" })));
            return true;
          }
        }
      } else {
        console.log(a.gray(`\u2139 ${fixResult.message}`));
      }
    }
    if (!skipPrompt) {
      const confirm = await promptBoolean({
        message: format(i18n.t("updater:confirmUpdate"), { tool: "Claude Code" }),
        defaultValue: true
      });
      if (!confirm) {
        console.log(a.gray(i18n.t("updater:updateSkipped")));
        return true;
      }
    } else {
      console.log(a.green(format(i18n.t("updater:autoUpdating"), { tool: "Claude Code" })));
    }
    const toolName = isHomebrew ? "Claude Code (Homebrew)" : "Claude Code";
    const updateSpinner = ora(format(i18n.t("updater:updating"), { tool: toolName })).start();
    try {
      if (isHomebrew) {
        const result = await q("brew", ["upgrade", "--cask", "claude-code"]);
        if (result.exitCode !== 0) {
          throw new Error(result.stderr || `Command failed with exit code ${result.exitCode}`);
        }
      } else {
        if (isBroken) {
          if (installationSource === "npm") {
            await execWithSudoIfNeeded("npm", ["install", "-g", "@anthropic-ai/claude-code"]);
          } else if (installationSource === "curl") {
            const { detectAllClaudeCodeInstallations } = await import('./version-checker.mjs');
            const installations = await detectAllClaudeCodeInstallations();
            const curlInstall = installations.find((i) => i.source === "curl" && i.version);
            if (curlInstall?.path) {
              await execWithSudoIfNeeded(curlInstall.path, ["update"]);
            } else {
              throw new Error(i18n.t("updater:curlReinstallRequired"));
            }
          } else {
            const { detectAllClaudeCodeInstallations } = await import('./version-checker.mjs');
            const installations = await detectAllClaudeCodeInstallations();
            const activeInstall = installations.find((i) => i.version);
            if (activeInstall?.path) {
              await execWithSudoIfNeeded(activeInstall.path, ["update"]);
            } else {
              throw new Error(i18n.t("updater:curlReinstallRequired"));
            }
          }
        } else {
          await execWithSudoIfNeeded("claude", ["update"]);
        }
      }
      const { commandExists } = await import('./platform.mjs').then(function (n) { return n.p; });
      const claudeWorks = await commandExists("claude");
      if (claudeWorks) {
        updateSpinner.succeed(format(i18n.t("updater:updateSuccess"), { tool: "Claude Code" }));
      } else {
        updateSpinner.warn(format(i18n.t("updater:updateSuccess"), { tool: "Claude Code" }));
        console.log(a.yellow("  \u26A0 claude command not found in PATH after update"));
        console.log(a.gray("  Try: npm install -g @anthropic-ai/claude-code"));
      }
      return claudeWorks;
    } catch (error) {
      updateSpinner.fail(format(i18n.t("updater:updateFailed"), { tool: "Claude Code" }));
      console.error(a.red(error instanceof Error ? error.message : String(error)));
      return false;
    }
  } catch (error) {
    spinner.fail(i18n.t("updater:checkFailed"));
    console.error(a.red(error instanceof Error ? error.message : String(error)));
    return false;
  }
}
async function updateCometixLine(force = false, skipPrompt = false) {
  ensureI18nInitialized();
  const spinner = ora(i18n.t("updater:checkingVersion")).start();
  try {
    const { installed, currentVersion, latestVersion, needsUpdate } = await checkCometixLineVersion();
    spinner.stop();
    if (!installed) {
      console.log(a.yellow(i18n.t("updater:cometixLineNotInstalled")));
      return false;
    }
    if (!needsUpdate && !force) {
      console.log(a.green(format(i18n.t("updater:cometixLineUpToDate"), { version: currentVersion || "" })));
      return true;
    }
    if (!latestVersion) {
      console.log(a.yellow(i18n.t("updater:cannotCheckVersion")));
      return false;
    }
    console.log(a.green(format(i18n.t("updater:currentVersion"), { version: currentVersion || "" })));
    console.log(a.green(format(i18n.t("updater:latestVersion"), { version: latestVersion })));
    if (!skipPrompt) {
      const confirm = await promptBoolean({
        message: format(i18n.t("updater:confirmUpdate"), { tool: "CCometixLine" }),
        defaultValue: true
      });
      if (!confirm) {
        console.log(a.gray(i18n.t("updater:updateSkipped")));
        return true;
      }
    } else {
      console.log(a.green(format(i18n.t("updater:autoUpdating"), { tool: "CCometixLine" })));
    }
    const updateSpinner = ora(format(i18n.t("updater:updating"), { tool: "CCometixLine" })).start();
    try {
      await execWithSudoIfNeeded("npm", ["update", "-g", "@cometix/ccline"]);
      updateSpinner.succeed(format(i18n.t("updater:updateSuccess"), { tool: "CCometixLine" }));
      return true;
    } catch (error) {
      updateSpinner.fail(format(i18n.t("updater:updateFailed"), { tool: "CCometixLine" }));
      console.error(a.red(error instanceof Error ? error.message : String(error)));
      return false;
    }
  } catch (error) {
    spinner.fail(i18n.t("updater:checkFailed"));
    console.error(a.red(error instanceof Error ? error.message : String(error)));
    return false;
  }
}
async function updateMyclaude(force = false, skipPrompt = false) {
  ensureI18nInitialized();
  const spinner = ora(i18n.t("updater:checkingVersion")).start();
  try {
    const { installed, currentVersion, latestVersion, needsUpdate } = await checkMyclaudeVersion();
    spinner.stop();
    if (!installed) {
      console.log(a.yellow("Clavue is not installed"));
      return false;
    }
    if (!needsUpdate && !force) {
      console.log(a.green(`Clavue is up to date (v${currentVersion || ""})`));
      return true;
    }
    if (!latestVersion) {
      console.log(a.yellow(i18n.t("updater:cannotCheckVersion")));
      return false;
    }
    console.log(a.green(format(i18n.t("updater:currentVersion"), { version: currentVersion || "" })));
    console.log(a.green(format(i18n.t("updater:latestVersion"), { version: latestVersion })));
    if (!skipPrompt) {
      const confirm = await promptBoolean({
        message: format(i18n.t("updater:confirmUpdate"), { tool: "clavue" }),
        defaultValue: true
      });
      if (!confirm) {
        console.log(a.gray(i18n.t("updater:updateSkipped")));
        return true;
      }
    } else {
      console.log(a.green(format(i18n.t("updater:autoUpdating"), { tool: "clavue" })));
    }
    const updateSpinner = ora(format(i18n.t("updater:updating"), { tool: "clavue" })).start();
    try {
      await execWithSudoIfNeeded("npm", ["update", "-g", "clavue"]);
      const verifyResult = await q("clavue", ["--version"]);
      if (verifyResult.exitCode !== 0) {
        throw new Error(verifyResult.stderr || `Command failed with exit code ${verifyResult.exitCode}`);
      }
      updateSpinner.succeed(format(i18n.t("updater:updateSuccess"), { tool: "clavue" }));
      return true;
    } catch (error) {
      updateSpinner.fail(format(i18n.t("updater:updateFailed"), { tool: "clavue" }));
      console.error(a.red(error instanceof Error ? error.message : String(error)));
      return false;
    }
  } catch (error) {
    spinner.fail(i18n.t("updater:checkFailed"));
    console.error(a.red(error instanceof Error ? error.message : String(error)));
    return false;
  }
}
async function checkAndUpdateTools(skipPrompt = false) {
  ensureI18nInitialized();
  console.log(a.bold.cyan(`
\u{1F50D} ${i18n.t("updater:checkingTools")}
`));
  try {
    const duplicateResult = await handleDuplicateInstallations(skipPrompt);
    if (duplicateResult.hadDuplicates) {
      console.log();
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.warn(a.yellow(`\u26A0 Duplicate installation check failed: ${errorMessage}`));
  }
  const results = [];
  let ccjkUpdated = false;
  let ccjkResult = null;
  console.log(a.bold("\u{1F500} CCR"));
  try {
    const success = await updateCcr(false, skipPrompt);
    results.push({ tool: "CCR", success });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error(a.red(`\u274C ${format(i18n.t("updater:updateFailed"), { tool: "CCR" })}: ${errorMessage}`));
    results.push({ tool: "CCR", success: false, error: errorMessage });
  }
  console.log();
  try {
    const success = await updateClaudeCode(false, skipPrompt);
    results.push({ tool: "Claude Code", success });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error(a.red(`\u274C ${format(i18n.t("updater:updateFailed"), { tool: "Claude Code" })}: ${errorMessage}`));
    results.push({ tool: "Claude Code", success: false, error: errorMessage });
  }
  console.log();
  try {
    const success = await updateCometixLine(false, skipPrompt);
    results.push({ tool: "CCometixLine", success });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error(a.red(`\u274C ${format(i18n.t("updater:updateFailed"), { tool: "CCometixLine" })}: ${errorMessage}`));
    results.push({ tool: "CCometixLine", success: false, error: errorMessage });
  }
  console.log();
  console.log(a.bold("\u{1F4E6} CCJK"));
  try {
    const result = await checkCcjkVersionAndPrompt(skipPrompt);
    ccjkUpdated = result.updated;
    ccjkResult = {
      tool: "CCJK",
      success: result.success,
      error: result.error
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error(a.red(`\u274C ${format(i18n.t("updater:updateFailed"), { tool: "CCJK" })}: ${errorMessage}`));
    ccjkResult = { tool: "CCJK", success: false, error: errorMessage };
  }
  console.log(a.bold.cyan(`
\u{1F4CB} ${i18n.t("updater:updateSummary")}`));
  for (const result of ccjkResult ? [ccjkResult, ...results] : results) {
    if (result.success) {
      console.log(a.green(`\u2714 ${result.tool}: ${i18n.t("updater:success")}`));
    } else {
      console.log(a.red(`\u274C ${result.tool}: ${i18n.t("updater:failed")} ${result.error ? `(${result.error})` : ""}`));
    }
  }
  if (ccjkUpdated) {
    console.log(a.yellow("\n\u26A0 Please run ccjk again to use the new version"));
    process.exit(0);
  }
}
async function checkAndUpdateMyclaudeTools(skipPrompt = false) {
  ensureI18nInitialized();
  console.log(a.bold.cyan(`
\u{1F50D} ${i18n.t("updater:checkingTools")}
`));
  const results = [];
  let ccjkUpdated = false;
  let ccjkResult = null;
  console.log(a.bold("\u2728 Clavue"));
  try {
    const success = await updateMyclaude(false, skipPrompt);
    results.push({ tool: "clavue", success });
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error(a.red(`\u274C ${format(i18n.t("updater:updateFailed"), { tool: "clavue" })}: ${errorMessage}`));
    results.push({ tool: "clavue", success: false, error: errorMessage });
  }
  console.log();
  console.log(a.bold("\u{1F4E6} CCJK"));
  try {
    const result = await checkCcjkVersionAndPrompt(skipPrompt);
    ccjkUpdated = result.updated;
    ccjkResult = {
      tool: "CCJK",
      success: result.success,
      error: result.error
    };
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error(a.red(`\u274C ${format(i18n.t("updater:updateFailed"), { tool: "CCJK" })}: ${errorMessage}`));
    ccjkResult = { tool: "CCJK", success: false, error: errorMessage };
  }
  console.log(a.bold.cyan(`
\u{1F4CB} ${i18n.t("updater:updateSummary")}`));
  for (const result of ccjkResult ? [ccjkResult, ...results] : results) {
    if (result.success) {
      console.log(a.green(`\u2714 ${result.tool}: ${i18n.t("updater:success")}`));
    } else {
      console.log(a.red(`\u274C ${result.tool}: ${i18n.t("updater:failed")} ${result.error ? `(${result.error})` : ""}`));
    }
  }
  if (ccjkUpdated) {
    console.log(a.yellow("\n\u26A0 Please run ccjk again to use the new version"));
    process.exit(0);
  }
}
async function checkCcjkVersionAndPrompt(_skipPrompt) {
  try {
    const { readFileSync } = await import('node:fs');
    const { fileURLToPath } = await import('node:url');
    const { dirname, join } = await import('./index10.mjs');
    const __dirname = dirname(fileURLToPath(import.meta.url));
    const pkgPath = join(__dirname, "..", "..", "package.json");
    const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
    const currentVersion = pkg.version;
    console.log(a.cyan(`${i18n.t("updater:currentVersion")} v${currentVersion}`));
    const { stdout } = await q("npm", ["view", "ccjk", "version"]);
    const latestVersion = stdout.trim();
    console.log(a.cyan(`${i18n.t("updater:latestVersion")} v${latestVersion}`));
    if (currentVersion === latestVersion) {
      console.log(a.green(`\u2713 ${i18n.t("updater:alreadyLatest")}`));
      return { success: true, updated: false };
    }
    console.log(a.green(`\u2714 ${i18n.t("updater:updatePrompt")} Yes`));
    console.log(a.dim("Clearing npx cache..."));
    try {
      await q("npm", ["cache", "clean", "--force"]);
    } catch {
    }
    const ora2 = (await import('./index8.mjs')).default;
    const updateSpinner = ora2("Updating CCJK...").start();
    try {
      await execWithSudoIfNeeded("npm", ["install", "-g", "ccjk@latest", "--force"]);
      updateSpinner.succeed(a.green(`\u2713 CCJK updated to v${latestVersion}`));
      return { success: true, updated: true };
    } catch (error) {
      const errorMessage = error instanceof Error ? error.message : String(error);
      updateSpinner.fail(a.red("\u2717 CCJK update failed"));
      console.error(a.red(errorMessage));
      console.log(a.gray("\nTry manually: npm install -g ccjk@latest"));
      return { success: false, updated: false, error: errorMessage };
    }
  } catch (error) {
    const errorMessage = error instanceof Error ? error.message : String(error);
    console.error(a.red(`${i18n.t("updater:checkFailed")} ${errorMessage}`));
    return { success: false, updated: false, error: errorMessage };
  }
}

export { checkAndUpdateMyclaudeTools, checkAndUpdateTools, execWithSudoIfNeeded, updateCcr, updateClaudeCode, updateCometixLine, updateMyclaude };
