import { storeKey, readKey, deleteKey, listProviders, PICKER_PROVIDERS } from "../../../security/key-store.js";
import { writePersistedConfig, defaultConfigPath } from "../../../persisted-config.js";
async function storeProviderKey(provider, value, opts) {
  try {
    const result = await storeKey(provider, value, opts);
    return { ok: true, location: result.location };
  } catch (err) {
    return { ok: false, error: err instanceof Error ? err.message : String(err) };
  }
}
async function readProviderKey(provider, opts) {
  const result = await readKey(provider, opts);
  if (result === null) return null;
  return {
    masked: maskValue(result.value),
    location: result.location
  };
}
async function deleteProviderKey(provider, opts) {
  try {
    await deleteKey(provider, opts);
    return { ok: true };
  } catch (err) {
    return { ok: false, error: err instanceof Error ? err.message : String(err) };
  }
}
async function listConfiguredProviders(opts) {
  const list = await listProviders(opts);
  return list;
}
async function saveProviderSelection(provider, value, opts, configPath = defaultConfigPath()) {
  const trimmed = value.trim();
  if (!trimmed) {
    return { ok: false, location: null, error: "value cannot be empty" };
  }
  if (provider === "custom") {
    try {
      writePersistedConfig(configPath, {
        provider: { name: "custom", keyLocation: "env" },
        settings: { WIGOLO_LLM_PROVIDER: trimmed }
      });
      return { ok: true, location: null };
    } catch (err) {
      return { ok: false, location: null, error: err instanceof Error ? err.message : String(err) };
    }
  }
  const stored = await storeProviderKey(provider, trimmed, opts);
  if (!stored.ok || !stored.location) {
    return { ok: false, location: null, error: stored.error ?? "failed to store key" };
  }
  try {
    writePersistedConfig(configPath, {
      provider: { name: provider, keyLocation: stored.location }
    });
  } catch (err) {
    return { ok: false, location: stored.location, error: err instanceof Error ? err.message : String(err) };
  }
  return { ok: true, location: stored.location };
}
function maskValue(value) {
  if (value.length <= 4) return "*".repeat(value.length);
  const show = Math.min(8, Math.ceil(value.length * 0.25));
  return value.slice(0, show) + "*".repeat(Math.max(4, value.length - show));
}
export {
  PICKER_PROVIDERS,
  deleteProviderKey,
  listConfiguredProviders,
  maskValue,
  readProviderKey,
  saveProviderSelection,
  storeProviderKey
};
//# sourceMappingURL=provider-keys.js.map