// Crucix Configuration — all settings with env var overrides

import "./apis/utils/env.mjs"; // Load .env first

function intEnv(name, fallback) {
  const value = parseInt(process.env[name], 10);
  return Number.isFinite(value) ? value : fallback;
}

function floatEnv(name, fallback) {
  const value = parseFloat(process.env[name]);
  return Number.isFinite(value) ? value : fallback;
}

function boolEnv(name, fallback = false) {
  const value = process.env[name];
  if (value == null || value === '') return fallback;
  return ['1', 'true', 'yes', 'on'].includes(String(value).toLowerCase());
}

export default {
  port: intEnv('PORT', 3117),
  refreshIntervalMinutes: intEnv('REFRESH_INTERVAL_MINUTES', 15),
  autoOpenBrowser: boolEnv('AUTO_OPEN_BROWSER', false),
  staleDataMaxAgeMinutes: intEnv('STALE_DATA_MAX_AGE_MINUTES', 60),
  staleAlertCooldownMinutes: intEnv('STALE_ALERT_COOLDOWN_MINUTES', 60),
  dashboardUrl: process.env.DASHBOARD_URL || null,
  sweepToken: process.env.SWEEP_TOKEN || null,
  terminalActionsEnabled: boolEnv('TERMINAL_ACTIONS_ENABLED', !!process.env.SWEEP_TOKEN || process.env.NODE_ENV !== 'production'),
  terminalActionRateLimitWindowMs: intEnv('TERMINAL_ACTION_RATE_LIMIT_WINDOW_MS', 60_000),
  terminalActionRateLimitMax: intEnv('TERMINAL_ACTION_RATE_LIMIT_MAX', 10),
  sseHeartbeatIntervalMs: intEnv('SSE_HEARTBEAT_INTERVAL_MS', 25000),

  security: {
    onboardingEnabled: boolEnv('SECURITY_ONBOARDING_ENABLED', true),
    profileEncryptionKey: process.env.SECURITY_PROFILE_ENCRYPTION_KEY || null,
  },

  davePresence: {
    enabled: boolEnv('DAVE_PRESENCE_ENABLED', false),
    maxPerDay: intEnv('DAVE_PRESENCE_MAX_MESSAGES_PER_DAY', 4),
    minGapMinutes: intEnv('DAVE_PRESENCE_MIN_GAP_MINUTES', 75),
    minIntervalMinutes: intEnv('DAVE_PRESENCE_MIN_INTERVAL_MINUTES', 45),
    maxIntervalMinutes: intEnv('DAVE_PRESENCE_MAX_INTERVAL_MINUTES', 180),
    idleAfterMinutes: intEnv('DAVE_PRESENCE_IDLE_AFTER_MINUTES', 60),
    checkIntervalMinutes: intEnv('DAVE_PRESENCE_CHECK_INTERVAL_MINUTES', 5),
    timezone: process.env.DAVE_PRESENCE_TIMEZONE || 'Europe/Berlin',
  },

  llm: {
    provider: process.env.LLM_PROVIDER || null, // litellm | openrouter | openai-compatible | lmstudio | ollama | other supported providers
    apiKey: process.env.LLM_API_KEY || null,
    model: process.env.LLM_MODEL || null,
    baseUrl: process.env.LLM_BASE_URL || process.env.OPENAI_BASE_URL || process.env.OLLAMA_BASE_URL || null,
    temperature: floatEnv('LLM_TEMPERATURE', 0.2),
    maxTokens: intEnv('LLM_MAX_TOKENS', 2000),
    timeoutMs: intEnv('LLM_TIMEOUT_MS', 90000),
    openRouterSiteUrl: process.env.OPENROUTER_SITE_URL || 'https://git.wilkensxl.de/Code-Inc/intelligence-terminal',
    openRouterAppName: process.env.OPENROUTER_APP_NAME || 'Intelligence Terminal',
  },

  telegram: {
    botToken: process.env.TELEGRAM_BOT_TOKEN || null,
    chatId: process.env.TELEGRAM_CHAT_ID || null,
    botPollingInterval: intEnv('TELEGRAM_POLL_INTERVAL', 5000),
    channels: process.env.TELEGRAM_CHANNELS || null, // Comma-separated extra channel IDs
    briefVerbosity: process.env.BRIEF_VERBOSITY || 'standard',
    aiChatEnabled: boolEnv('TELEGRAM_AI_CHAT_ENABLED', true),
    aiHistoryMessages: intEnv('TELEGRAM_AI_HISTORY_MESSAGES', 8),
    aiMaxInputChars: intEnv('TELEGRAM_AI_MAX_INPUT_CHARS', 2000),
    aiMaxTokens: intEnv('TELEGRAM_AI_MAX_TOKENS', 2048),
    aiTimeoutMs: intEnv('TELEGRAM_AI_TIMEOUT_MS', 300000),
    agentEnabled: boolEnv('TELEGRAM_AGENT_ENABLED', true),
    agentMaxSteps: intEnv('TELEGRAM_AGENT_MAX_STEPS', 4),
    agentConfirmationTtlSeconds: intEnv('TELEGRAM_AGENT_CONFIRM_TTL_SECONDS', 300),
    agentProactiveEnabled: boolEnv('TELEGRAM_AGENT_PROACTIVE_ENABLED', true),
    agentProactiveMinChanges: intEnv('TELEGRAM_AGENT_PROACTIVE_MIN_CHANGES', 3),
    agentProactiveCooldownMinutes: intEnv('TELEGRAM_AGENT_PROACTIVE_COOLDOWN_MINUTES', 30),
  },

  discord: {
    botToken: process.env.DISCORD_BOT_TOKEN || null,
    channelId: process.env.DISCORD_CHANNEL_ID || null,
    guildId: process.env.DISCORD_GUILD_ID || null, // Server ID (for instant slash command registration)
    webhookUrl: process.env.DISCORD_WEBHOOK_URL || null, // Fallback: webhook-only alerts (no bot needed)
  },

  // Delta engine thresholds — override defaults from lib/delta/engine.mjs
  // Set to null to use built-in defaults
  delta: {
    thresholds: {
      numeric: {
        // Example overrides (uncomment to customize):
        // vix: 3,       // more sensitive to VIX moves
        // wti: 5,       // less sensitive to oil moves
      },
      count: {
        // urgent_posts: 3,     // need ±3 urgent posts to flag
        // thermal_total: 1000, // need ±1000 thermal detections
      },
    },
  },
};
