// src/actions/lint-config.ts
import { readFileSync as readFileSync2, writeFileSync } from "node:fs";
import chalk2 from "chalk";
import { findUpSync as findUpSync2 } from "find-up";

// src/lib/initCwd.ts
function INIT_CWD() {
  return process.env.INIT_CWD ?? process.cwd();
}

// src/lib/reporting/runWithEnvelope.ts
import { performance as performance2 } from "node:perf_hooks";

// src/lib/reporting/xyReporter.ts
import { performance } from "node:perf_hooks";
var reporterState = {
  currentCommand: "unknown",
  isEnvelopeEmitted: false,
  isJsonModeEnabled: false,
  isStrictModeEnabled: false,
  originalStdoutWrite: void 0,
  startTime: 0
};
function isJsonMode() {
  return reporterState.isJsonModeEnabled;
}
function setCurrentCommand(name) {
  reporterState.currentCommand = name;
  reporterState.startTime = performance.now();
  reporterState.isEnvelopeEmitted = false;
}
function emitJson(envelope) {
  if (reporterState.isEnvelopeEmitted) return;
  reporterState.isEnvelopeEmitted = true;
  const json = JSON.stringify(envelope) + "\n";
  if (reporterState.originalStdoutWrite) {
    reporterState.originalStdoutWrite(json);
  } else {
    process.stdout.write(json);
  }
}

// src/lib/reporting/runWithEnvelope.ts
async function runWithEnvelope(command, action) {
  setCurrentCommand(command);
  const start = performance2.now();
  let exitCode;
  let envelope;
  try {
    const ret = await action();
    if (typeof ret === "number") {
      exitCode = ret;
    } else {
      exitCode = ret.exitCode;
      envelope = ret.envelope;
    }
  } catch (ex) {
    exitCode = 1;
    const message = ex instanceof Error ? ex.message : String(ex);
    envelope = {
      errorCount: 1,
      errors: [{ message }]
    };
    if (!isJsonMode()) {
      console.error(message);
    }
  }
  if (isJsonMode()) {
    emitJson({
      command,
      data: envelope?.data,
      durationMs: Math.round(performance2.now() - start),
      errorCount: envelope?.errorCount ?? (exitCode === 0 ? 0 : 1),
      errors: envelope?.errors,
      exitCode,
      schemaVersion: 1,
      success: exitCode === 0,
      warningCount: envelope?.warningCount ?? 0,
      warnings: envelope?.warnings
    });
  }
  return exitCode;
}
async function withEnvelope(command, action) {
  process.exitCode = await runWithEnvelope(command, action);
}

// src/actions/lintTierAnalysis.ts
import { readFileSync } from "node:fs";
import chalk from "chalk";
import { findUpSync } from "find-up";
var tierExportPattern = /config(?:React)?Tier\d+[A-Za-z]*/g;
var composedConfigModules = [
  "bestPracticesCoreConfig",
  "consistencyRulesConfig",
  "correctnessCoreConfig",
  "importConfig",
  "rulesConfig",
  "typescriptConfig",
  "typescriptConsistencyConfig",
  "typescriptCorrectnessConfig",
  "typescriptTypeCheckedConfig",
  "typescriptTypeCheckedConsistencyConfig",
  "typescriptTypeCheckedCorrectnessConfig",
  "unicornConfig",
  "workspacesConfig"
];
function escapeRegExp(value) {
  return value.replaceAll(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`);
}
function hasComposedConfigModules(source) {
  return composedConfigModules.some((module) => source.includes(module));
}
function resolveLintTierConfigKind(source, currentTierExport) {
  if (currentTierExport === void 0) return "custom";
  const presetExportPattern = RegExp(String.raw`export\s+default\s+${escapeRegExp(currentTierExport)}\b`);
  if (presetExportPattern.test(source)) return "preset";
  if (hasComposedConfigModules(source)) return "custom";
  if (source.includes(`...${currentTierExport}`)) return "preset";
  return "custom";
}
function detectLintTierContext(cwd) {
  const configPath = findUpSync("eslint.config.ts", { cwd });
  if (configPath === void 0) {
    return {
      configKind: "custom",
      hasXylabsConfig: false,
      isReact: false,
      isTypeChecked: true
    };
  }
  const source = readFileSync(configPath, "utf8");
  const hasXylabsConfig = source.includes("@xylabs/eslint-config-flat") || source.includes("@xylabs/eslint-config-react-flat");
  const isReact = source.includes("@xylabs/eslint-config-react-flat");
  const isTypeChecked = /(?:config(?:React)?Tier\d+\w*TypeChecked|typescriptTypeCheckedConfig)/.test(source);
  const tierMatches = source.match(tierExportPattern) ?? [];
  const currentTierExport = tierMatches.at(-1);
  const configKind = resolveLintTierConfigKind(source, currentTierExport);
  return {
    configKind,
    currentTierExport,
    hasXylabsConfig,
    isReact,
    isTypeChecked
  };
}

// src/actions/lint-config.ts
var lintConfigSettings = ["type-checked"];
var tierExportPattern2 = /config(?:React)?Tier\d+[A-Za-z]*/g;
function isLintConfigSetting(setting) {
  return lintConfigSettings.includes(setting);
}
function resolveEslintConfigPath(cwd) {
  const configPath = findUpSync2(["eslint.config.ts", "eslint.config.mjs"], { cwd });
  if (configPath === void 0) {
    throw new Error("eslint.config.ts not found");
  }
  return configPath;
}
function readEslintConfigSource(cwd) {
  const configPath = resolveEslintConfigPath(cwd);
  return {
    configPath,
    source: readFileSync2(configPath, "utf8")
  };
}
function assertXylabsEslintConfig(cwd) {
  const context = detectLintTierContext(cwd);
  if (!context.hasXylabsConfig) {
    throw new Error("eslint.config.ts must use @xylabs/eslint-config-flat or @xylabs/eslint-config-react-flat");
  }
}
function getLintConfigValue(cwd, setting) {
  assertXylabsEslintConfig(cwd);
  switch (setting) {
    case "type-checked": {
      return detectLintTierContext(cwd).isTypeChecked ? "true" : "false";
    }
    default: {
      const unsupported = setting;
      throw new Error(`Unsupported lint config setting "${unsupported}"`);
    }
  }
}
function isLintConfigFlagTruthy(value) {
  if (value === void 0) return true;
  const normalized = value.trim().toLowerCase();
  if (["true", "on", "yes", "1", "enable", "enabled"].includes(normalized)) return true;
  if (["false", "off", "no", "0", "disable", "disabled"].includes(normalized)) return false;
  throw new Error(`Invalid boolean value "${value}" (expected true/false, on/off, yes/no, or 1/0)`);
}
function transformTierPresetNames(source, isEnabled) {
  const exports = [...new Set(source.match(tierExportPattern2))];
  let result = source;
  for (const exportName of exports) {
    const next = isEnabled ? exportName.endsWith("TypeChecked") ? exportName : `${exportName}TypeChecked` : exportName.replace(/TypeChecked$/, "");
    if (next !== exportName) {
      result = result.split(exportName).join(next);
    }
  }
  return result;
}
function transformTypescriptModuleNames(source, isEnabled) {
  if (isEnabled) {
    if (source.includes("typescriptTypeCheckedConfig")) return source;
    return source.replaceAll(/\btypescriptConfig\b/g, "typescriptTypeCheckedConfig");
  }
  if (!source.includes("typescriptTypeCheckedConfig")) return source;
  return source.replaceAll(/\btypescriptTypeCheckedConfig\b/g, "typescriptConfig");
}
function applyTypeCheckedSetting(source, isEnabled) {
  return transformTypescriptModuleNames(transformTierPresetNames(source, isEnabled), isEnabled);
}
function setLintConfigValue(cwd, setting, value) {
  assertXylabsEslintConfig(cwd);
  if (setting !== "type-checked") {
    const unsupported = setting;
    throw new Error(`Unsupported lint config setting "${unsupported}"`);
  }
  const isEnabled = isLintConfigFlagTruthy(value);
  const { configPath, source } = readEslintConfigSource(cwd);
  const isCurrent = detectLintTierContext(cwd).isTypeChecked;
  if (isCurrent === isEnabled) {
    console.log(chalk2.gray(`type-checked is already ${isEnabled ? "enabled" : "disabled"}`));
    return 0;
  }
  const nextSource = applyTypeCheckedSetting(source, isEnabled);
  writeFileSync(configPath, nextSource, "utf8");
  console.log(chalk2.green(`Updated ${configPath}: type-checked ${isEnabled ? "enabled" : "disabled"}`));
  return 0;
}
function lintConfigGet(setting) {
  if (!isLintConfigSetting(setting)) {
    console.error(chalk2.red(`Unknown lint config setting "${setting}". Supported: ${lintConfigSettings.join(", ")}`));
    return 1;
  }
  try {
    console.log(getLintConfigValue(INIT_CWD(), setting));
    return 0;
  } catch (ex) {
    console.error(chalk2.red(ex instanceof Error ? ex.message : String(ex)));
    return 1;
  }
}
function lintConfigSet(setting, value) {
  if (!isLintConfigSetting(setting)) {
    console.error(chalk2.red(`Unknown lint config setting "${setting}". Supported: ${lintConfigSettings.join(", ")}`));
    return 1;
  }
  try {
    return setLintConfigValue(INIT_CWD(), setting, value);
  } catch (ex) {
    console.error(chalk2.red(ex instanceof Error ? ex.message : String(ex)));
    return 1;
  }
}

// src/xy/lint/lint/configCommand.ts
var configGetCommand = {
  command: "get <setting>",
  describe: "Read a lint configuration value",
  handler: async (argv) => {
    await withEnvelope("lint config get", () => lintConfigGet(argv.setting));
  }
};
var configSetCommand = {
  builder: (yargs) => {
    return yargs.positional("value", {
      describe: "Boolean value (true/false, on/off, yes/no, 1/0). Defaults to true when omitted.",
      type: "string"
    });
  },
  command: "set <setting> [value]",
  describe: "Update a lint configuration value",
  handler: async (argv) => {
    await withEnvelope("lint config set", () => lintConfigSet(argv.setting, argv.value));
  }
};
var configCommand = {
  builder: (yargs) => {
    return yargs.command(configGetCommand).command(configSetCommand).demandCommand(1, "Specify get or set");
  },
  command: "config",
  describe: "Configure lint settings",
  handler: () => {
  }
};
export {
  configCommand,
  configGetCommand,
  configSetCommand
};
//# sourceMappingURL=configCommand.mjs.map
