import {
  jsonOk,
  routeWrap
} from "./chunk-ZMMFMEXX.js";
import {
  readSetting,
  writeSetting
} from "./chunk-2MAQ6JFL.js";
import {
  badRequest
} from "./chunk-EZYKRG4W.js";

// src/handlers/settings.ts
var NON_SECRET_KEYS = /* @__PURE__ */ new Set([
  "saved_repositories",
  // Provider identifiers (not credentials) — safe to surface in the API
  // so the UI can show "configured as team XYZ, project ABC".
  "vercel_team_id",
  "vercel_project_id",
  "fly_app_name",
  // Skills catalog URL overrides — URLs, not secrets.
  "skills_feed_url",
  "skills_index_url"
]);
var ALLOWED_KEYS = [
  // Engine + cloud provider credentials
  "sprite_token",
  "anthropic_api_key",
  "openai_api_key",
  "gemini_api_key",
  "factory_api_key",
  "claude_token",
  "e2b_api_key",
  "vercel_token",
  "daytona_api_key",
  "fly_api_token",
  "modal_token_id",
  "modal_token_secret",
  // Provider identifiers (not secrets but pair with credentials)
  "vercel_team_id",
  "vercel_project_id",
  "fly_app_name",
  // Skills catalog URL overrides (operator override; default is agentstep.com)
  "skills_feed_url",
  "skills_index_url",
  // UI state
  "saved_repositories"
];
var SECRET_KEYS = new Set(ALLOWED_KEYS.filter((k) => !NON_SECRET_KEYS.has(k)));
function maskSecret(value) {
  if (!value) return "";
  if (value.length <= 12) return "\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022";
  return `${value.slice(0, 6)}${"\u2022".repeat(Math.max(8, value.length - 10))}${value.slice(-4)}`;
}
function handlePutSetting(request) {
  return routeWrap(request, async () => {
    const body = await request.json().catch(() => null);
    if (!body?.key || typeof body.value !== "string") {
      throw badRequest("key and value are required");
    }
    if (!ALLOWED_KEYS.includes(body.key)) {
      throw badRequest(`setting "${body.key}" is not writable via API`);
    }
    writeSetting(body.key, body.value);
    return jsonOk({ ok: true });
  });
}
function handleGetSetting(request, key) {
  return routeWrap(request, async () => {
    if (!ALLOWED_KEYS.includes(key)) {
      throw badRequest(`setting "${key}" is not readable via API`);
    }
    const value = readSetting(key);
    if (value === void 0) {
      return jsonOk({ key, value: null, configured: false });
    }
    if (SECRET_KEYS.has(key)) {
      return jsonOk({ key, value: maskSecret(value), configured: true, masked: true });
    }
    return jsonOk({ key, value, configured: true });
  });
}

export {
  handlePutSetting,
  handleGetSetting
};
