import {
  init_clock,
  nowMs
} from "./chunk-HFDLUBWN.js";
import {
  getDrizzle,
  init_drizzle
} from "./chunk-RII4M3J2.js";
import {
  schema_exports
} from "./chunk-DDJOPRB7.js";

// src/config/index.ts
init_drizzle();
init_clock();
import { eq } from "drizzle-orm";
var g = globalThis;
var CACHE_MS = 3e4;
function readSetting(key) {
  try {
    const db = getDrizzle();
    const row = db.select().from(schema_exports.settings).where(eq(schema_exports.settings.key, key)).get();
    return row?.value ?? void 0;
  } catch {
    return void 0;
  }
}
function num(env, fallback) {
  if (env == null) return fallback;
  const n = Number(env);
  return Number.isFinite(n) ? n : fallback;
}
function loadConfig() {
  return {
    spriteToken: process.env.SPRITE_TOKEN || readSetting("sprite_token"),
    spriteApi: process.env.SPRITE_API || readSetting("sprite_api") || "https://api.sprites.dev",
    anthropicApiKey: process.env.ANTHROPIC_API_KEY || readSetting("anthropic_api_key"),
    claudeToken: process.env.CLAUDE_CODE_OAUTH_TOKEN || readSetting("claude_token"),
    openAiApiKey: process.env.OPENAI_API_KEY || readSetting("openai_api_key"),
    geminiApiKey: process.env.GEMINI_API_KEY || readSetting("gemini_api_key") || void 0,
    factoryApiKey: process.env.FACTORY_API_KEY || readSetting("factory_api_key") || void 0,
    defaultModel: process.env.DEFAULT_MODEL || readSetting("default_model") || "claude-sonnet-4-6",
    agentMaxTurns: num(process.env.AGENT_MAX_TURNS, 0),
    agentTimeoutMs: num(process.env.AGENT_TIMEOUT_MS, 18e5),
    spriteTimeoutMs: num(process.env.SPRITE_TIMEOUT_MS, 3e4),
    concurrency: num(process.env.CONCURRENCY, 4),
    maxSandboxesPerEnv: num(process.env.MAX_SANDBOXES_PER_ENV, 8),
    sessionMaxAgeMs: num(process.env.SESSION_MAX_AGE_MS, 3600 * 1e3),
    sweeperIntervalMs: num(process.env.SWEEPER_INTERVAL_MS, 6e4),
    otlpEndpoint: process.env.OTEL_EXPORTER_OTLP_ENDPOINT || process.env.OTLP_ENDPOINT || readSetting("otlp_endpoint") || void 0,
    otlpAuthorization: process.env.OTEL_EXPORTER_OTLP_HEADERS_AUTHORIZATION || process.env.OTLP_AUTHORIZATION || readSetting("otlp_authorization") || void 0,
    redactEnvKeys: (process.env.OBS_REDACT_KEYS || readSetting("obs_redact_keys") || "").split(",").map((s) => s.trim()).filter(Boolean),
    ollamaUrl: process.env.OLLAMA_URL || readSetting("ollama_url") || "http://localhost:11434",
    anthropicPassthroughEnabled: parseBool(
      process.env.ANTHROPIC_PASSTHROUGH_ENABLED ?? readSetting("anthropic_passthrough_enabled")
    ),
    warmPoolSize: num(process.env.WARM_POOL_SIZE, 0),
    warmPoolTtlMs: num(process.env.WARM_POOL_TTL_MS, 3e5),
    defaultProvider: process.env.DEFAULT_PROVIDER || readSetting("default_provider") || void 0
  };
}
function parseBool(v) {
  if (!v) return false;
  const s = v.toLowerCase();
  return s === "1" || s === "true" || s === "yes";
}
function getConfig() {
  const now = nowMs();
  if (g.__caConfigCache && now - g.__caConfigCache.at < CACHE_MS) {
    return g.__caConfigCache.value;
  }
  const value = loadConfig();
  g.__caConfigCache = { at: now, value };
  return value;
}
function invalidateConfigCache() {
  g.__caConfigCache = void 0;
}
function writeSetting(key, value) {
  const db = getDrizzle();
  const now = nowMs();
  db.insert(schema_exports.settings).values({ key, value, updated_at: now }).onConflictDoUpdate({ target: schema_exports.settings.key, set: { value, updated_at: now } }).run();
  invalidateConfigCache();
}
var TOKEN_TO_SETTING = {
  SPRITE_TOKEN: "sprite_token",
  ANTHROPIC_API_KEY: "anthropic_api_key",
  OPENAI_API_KEY: "openai_api_key",
  GEMINI_API_KEY: "gemini_api_key",
  FACTORY_API_KEY: "factory_api_key"
};
function writeTokenSetting(envVarName, value) {
  const settingKey = TOKEN_TO_SETTING[envVarName];
  if (settingKey) {
    writeSetting(settingKey, value);
  }
}
function readEnvOrSetting(envVarName) {
  const fromEnv = process.env[envVarName];
  if (fromEnv) return fromEnv;
  const settingKey = envVarName.toLowerCase();
  return readSetting(settingKey) || void 0;
}

export {
  readSetting,
  getConfig,
  invalidateConfigCache,
  writeSetting,
  writeTokenSetting,
  readEnvOrSetting
};
