function findField(catalog, key) {
  for (const category of catalog) {
    for (const field of category.fields) {
      if (field.key === key) return field;
    }
  }
  return null;
}
function coerceForField(field, raw) {
  if (field.kind === "number") {
    const n = Number(raw);
    return Number.isFinite(n) ? n : raw;
  }
  if (field.kind === "toggle") {
    if (raw === "true" || raw === "1" || raw.toLowerCase() === "on") return true;
    if (raw === "false" || raw === "0" || raw.toLowerCase() === "off") return false;
    return raw;
  }
  if (field.kind === "multiselect") {
    return raw.split(/[,\s]+/).map((s) => s.trim()).filter((s) => s.length > 0);
  }
  return raw;
}
function isSecretField(field) {
  return field.kind === "masked" || field.secret === true;
}
function emptyResult(status, message) {
  return { status, message, saved: [], propagated: [], failed: [] };
}
async function applyHeadlessSet(opts) {
  const field = findField(opts.catalog, opts.key);
  if (!field) {
    return emptyResult(
      "unknown_key",
      `Unknown setting: ${opts.key}. Run \`wigolo config --plain\` to list available keys.`
    );
  }
  if (isSecretField(field)) {
    return emptyResult(
      "secret_rejected",
      `Secrets cannot be set via --set (shell-history leak); use the interactive provider menu or set ${opts.key} via an env var.`
    );
  }
  const coerced = coerceForField(field, opts.value);
  if (field.validate) {
    const err = field.validate(coerced);
    if (err) {
      return emptyResult(
        "validation_failed",
        `Invalid value for ${opts.key}: ${err}`
      );
    }
  }
  let initial;
  if (opts.readSettings) {
    initial = opts.readSettings(opts.configPath);
  } else {
    const persistedMod = await import("../../../persisted-config.js");
    initial = persistedMod.readPersistedConfig(opts.configPath).settings;
  }
  let store;
  if (opts.storeFactory) {
    store = opts.storeFactory(initial);
  } else {
    const storeMod = await import("../state/settings-store.js");
    store = storeMod.createSettingsStore(initial);
  }
  store.set(field.settingsPath, coerced);
  if (!store.isDirty()) {
    return {
      status: "ok",
      message: `Set ${opts.key} = ${String(coerced)} (no change \u2014 value matches current setting).`,
      saved: [field.settingsPath],
      propagated: [],
      failed: []
    };
  }
  const save = opts.save ?? (async (so) => {
    const mod = await import("../state/propagation.js");
    return mod.save(so);
  });
  let result;
  try {
    result = await save({
      store,
      catalog: opts.catalog,
      configPath: opts.configPath,
      agents: opts.agents,
      secretStore: opts.secretStore,
      fs: opts.fs
    });
  } catch (err) {
    return emptyResult(
      "persist_failed",
      `Save failed for ${opts.key}: ${err instanceof Error ? err.message : String(err)}`
    );
  }
  if (result.errors && result.errors.length > 0) {
    const reason = result.errors.map((e) => `${e.key}: ${e.reason}`).join("; ");
    return emptyResult("validation_failed", `Invalid value for ${opts.key}: ${reason}`);
  }
  const propagatedSegment = result.propagated.length > 0 ? ` (propagated to: ${result.propagated.join(", ")}` : " (no agents propagated";
  const failedSegment = result.failed.length > 0 ? `; failed: ${result.failed.map((f) => `${f.agentId} \u2014 ${f.reason}`).join(", ")})` : ")";
  return {
    status: "ok",
    message: `Set ${opts.key} = ${String(coerced)}${propagatedSegment}${failedSegment}.`,
    saved: result.saved,
    propagated: result.propagated,
    failed: result.failed
  };
}
export {
  applyHeadlessSet
};
//# sourceMappingURL=headless-set.js.map