import a from '../chunks/index5.mjs';
import { ensureI18nInitialized, i18n } from '../chunks/index2.mjs';
import { r as resolveClaudeFamilySettingsTarget, h as hasInvalidStatusLineConfig, n as normalizeClaudeFamilySettings } from './ccjk.DDL-4C-k.mjs';
import { b as backupExistingConfig } from '../chunks/config.mjs';
import { exists } from '../chunks/fs-operations.mjs';
import { readJsonConfig, writeJsonConfig } from '../chunks/json-config.mjs';

function migrateSettingsForTokenRetrieval(codeTool) {
  ensureI18nInitialized();
  const target = resolveClaudeFamilySettingsTarget(codeTool);
  const result = {
    success: false,
    changes: [],
    backupPath: null,
    errors: []
  };
  try {
    if (!exists(target.settingsFile)) {
      result.errors.push(i18n.t("common:fileNotFound", { file: "settings.json" }));
      return result;
    }
    const settings = readJsonConfig(target.settingsFile);
    if (!settings) {
      result.errors.push(i18n.t("common:failedToReadFile", { file: "settings.json" }));
      return result;
    }
    let modified = false;
    const hasAdaptiveRouting = Boolean(
      settings.env?.ANTHROPIC_DEFAULT_HAIKU_MODEL || settings.env?.ANTHROPIC_DEFAULT_SONNET_MODEL || settings.env?.ANTHROPIC_DEFAULT_OPUS_MODEL
    );
    if (hasInvalidStatusLineConfig(settings)) {
      normalizeClaudeFamilySettings(settings);
      result.changes.push("Repaired invalid statusLine settings for Clavue compatibility");
      modified = true;
    }
    if (settings.env) {
      if (settings.env.ANTHROPIC_DEFAULT_HAIKU_MODEL && !settings.env.ANTHROPIC_SMALL_FAST_MODEL) {
        settings.env.ANTHROPIC_SMALL_FAST_MODEL = settings.env.ANTHROPIC_DEFAULT_HAIKU_MODEL;
        result.changes.push("Restored ANTHROPIC_SMALL_FAST_MODEL from ANTHROPIC_DEFAULT_HAIKU_MODEL for Haiku fast-path compatibility");
        modified = true;
      }
      if ("CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC" in settings.env) {
        delete settings.env.CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC;
        result.changes.push("Removed CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC (was blocking token retrieval)");
        modified = true;
      }
      if (settings.env.MCP_TIMEOUT) {
        const timeout = Number.parseInt(settings.env.MCP_TIMEOUT, 10);
        if (!Number.isNaN(timeout) && timeout > 2e4) {
          const oldValue = settings.env.MCP_TIMEOUT;
          settings.env.MCP_TIMEOUT = "15000";
          result.changes.push(`Reduced MCP_TIMEOUT from ${oldValue}ms to 15000ms (was causing slow failures)`);
          modified = true;
        }
      }
    }
    if (settings.model === "default") {
      delete settings.model;
      result.changes.push('Removed invalid settings.model value "default"');
      modified = true;
    }
    if (settings.model && hasAdaptiveRouting) {
      delete settings.model;
      result.changes.push("Removed settings.model to restore adaptive Haiku/Sonnet/Opus routing");
      modified = true;
    }
    if (!modified) {
      result.success = true;
      return result;
    }
    const backupPath = backupExistingConfig(target.codeTool);
    if (backupPath) {
      result.backupPath = backupPath;
    } else {
      result.errors.push("Failed to create backup (continuing anyway)");
    }
    normalizeClaudeFamilySettings(settings);
    writeJsonConfig(target.settingsFile, settings);
    result.success = true;
    return result;
  } catch (error) {
    result.errors.push(`Migration failed: ${error instanceof Error ? error.message : String(error)}`);
    return result;
  }
}
function needsMigration(codeTool) {
  try {
    const target = resolveClaudeFamilySettingsTarget(codeTool);
    if (!exists(target.settingsFile)) {
      return false;
    }
    const settings = readJsonConfig(target.settingsFile);
    if (!settings) {
      return false;
    }
    const hasInvalidStatusLine = hasInvalidStatusLineConfig(settings);
    if (!settings.env) {
      return hasInvalidStatusLine;
    }
    const hasProblematicVar = "CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC" in settings.env;
    const hasExcessiveTimeout = settings.env.MCP_TIMEOUT && Number.parseInt(settings.env.MCP_TIMEOUT, 10) > 2e4;
    const hasMissingHaikuFastCompat = Boolean(
      settings.env.ANTHROPIC_DEFAULT_HAIKU_MODEL && !settings.env.ANTHROPIC_SMALL_FAST_MODEL
    );
    const hasAdaptiveRouting = Boolean(
      settings.env.ANTHROPIC_DEFAULT_HAIKU_MODEL || settings.env.ANTHROPIC_DEFAULT_SONNET_MODEL || settings.env.ANTHROPIC_DEFAULT_OPUS_MODEL
    );
    const hasInvalidDefaultModel = settings.model === "default";
    const hasAdaptiveModelOverride = Boolean(settings.model && hasAdaptiveRouting);
    return Boolean(
      hasProblematicVar || hasExcessiveTimeout || hasMissingHaikuFastCompat || hasInvalidDefaultModel || hasAdaptiveModelOverride || hasInvalidStatusLine
    );
  } catch {
    return false;
  }
}
function displayMigrationResult(result) {
  ensureI18nInitialized();
  if (result.success) {
    if (result.changes.length > 0) {
      console.log(a.green(`
\u2705 ${i18n.t("common:configurationFixed")}
`));
      console.log(a.bold("Changes made:"));
      for (const change of result.changes) {
        console.log(a.gray(`  \u2022 ${change}`));
      }
      if (result.backupPath) {
        console.log(a.gray(`
\u{1F4E6} Backup created: ${result.backupPath}`));
      }
      console.log(a.yellow("\n\u26A0\uFE0F  Please restart Claude Code CLI for changes to take effect.\n"));
    } else {
      console.log(a.green(`
\u2705 ${i18n.t("common:noMigrationNeeded")}
`));
    }
  } else {
    console.log(a.red(`
\u274C ${i18n.t("common:migrationFailed")}
`));
    if (result.errors.length > 0) {
      console.log(a.bold("Errors:"));
      for (const error of result.errors) {
        console.log(a.red(`  \u2022 ${error}`));
      }
    }
    if (result.backupPath) {
      console.log(a.gray(`
\u{1F4E6} Backup available at: ${result.backupPath}`));
      console.log(a.gray("You can restore with: cp <backup-path>/settings.json ~/.claude/settings.json\n"));
    }
  }
}
async function promptMigration() {
  ensureI18nInitialized();
  const inquirer = await import('../chunks/index6.mjs').then(function (n) { return n.c; });
  console.log(a.yellow("\n\u26A0\uFE0F  Problematic configuration detected!\n"));
  console.log(a.gray("Your settings.json contains configurations that prevent Claude Code"));
  console.log(a.gray("from retrieving token counts, causing /compact failures.\n"));
  const { shouldMigrate } = await inquirer.default.prompt({
    type: "confirm",
    name: "shouldMigrate",
    message: "Would you like to fix these issues automatically? (backup will be created)",
    default: true
  });
  return shouldMigrate;
}

export { displayMigrationResult as d, migrateSettingsForTokenRetrieval as m, needsMigration as n, promptMigration as p };
