// ZCLAW 配置管理
import { z } from 'zod';

const ConfigSchema = z.object({
  // AI Provider
  ai: z.object({
    provider: z.enum(['zhipu', 'openai', 'local']).default('zhipu'),
    zhipuApiKey: z.string().default(''),
    openaiApiKey: z.string().default(''),
    openaiBaseUrl: z.string().default('https://api.openai.com/v1'),
    defaultModel: z.string().default('glm-4-flash'),
    maxTokens: z.number().default(4096),
    temperature: z.number().default(0.7),
  }),

  // Database
  db: z.object({
    path: z.string().default('./data/zclaw.db'),
  }),

  // Server
  server: z.object({
    port: z.number().default(3721),
    host: z.string().default('127.0.0.1'),
  }),

  // IM Channels
  im: z.object({
    feishu: z.object({
      appId: z.string().default(''),
      appSecret: z.string().default(''),
      enabled: z.boolean().default(false),
    }),
    telegram: z.object({
      botToken: z.string().default(''),
      enabled: z.boolean().default(false),
    }),
  }),

  // Execution
  execution: z.object({
    maxConcurrent: z.number().default(5),
    taskTimeout: z.number().default(300000), // 5 minutes
    retryAttempts: z.number().default(3),
  }),

  // Memory
  memory: z.object({
    maxEventsPerUser: z.number().default(10000),
    embeddingModel: z.string().default('text-embedding-3-small'),
  }),

  // Logging
  log: z.object({
    level: z.enum(['debug', 'info', 'warn', 'error']).default('info'),
  }),
});

export type ZClawConfig = z.infer<typeof ConfigSchema>;

let _config: ZClawConfig | null = null;

export function loadConfig(overrides?: Partial<Record<string, any>>): ZClawConfig {
  const env = process.env;

  const raw = {
    ai: {
      provider: env.ZCLAW_AI_PROVIDER || 'zhipu',
      zhipuApiKey: env.ZCLAW_ZHIPU_API_KEY || env.ZHIPU_API_KEY || '',
      openaiApiKey: env.ZCLAW_OPENAI_API_KEY || env.OPENAI_API_KEY || '',
      openaiBaseUrl: env.ZCLAW_OPENAI_BASE_URL || 'https://api.openai.com/v1',
      defaultModel: env.ZCLAW_DEFAULT_MODEL || 'glm-4-flash',
      maxTokens: parseInt(env.ZCLAW_MAX_TOKENS || '4096'),
      temperature: parseFloat(env.ZCLAW_TEMPERATURE || '0.7'),
    },
    db: {
      path: env.ZCLAW_DB_PATH || './data/zclaw.db',
    },
    server: {
      port: parseInt(env.ZCLAW_PORT || '3721'),
      host: env.ZCLAW_HOST || '127.0.0.1',
    },
    im: {
      feishu: {
        appId: env.ZCLAW_FEISHU_APP_ID || '',
        appSecret: env.ZCLAW_FEISHU_APP_SECRET || '',
        enabled: env.ZCLAW_FEISHU_ENABLED === 'true',
      },
      telegram: {
        botToken: env.ZCLAW_TELEGRAM_BOT_TOKEN || '',
        enabled: env.ZCLAW_TELEGRAM_ENABLED === 'true',
      },
    },
    execution: {
      maxConcurrent: parseInt(env.ZCLAW_MAX_CONCURRENT || '5'),
      taskTimeout: parseInt(env.ZCLAW_TASK_TIMEOUT || '300000'),
      retryAttempts: parseInt(env.ZCLAW_RETRY_ATTEMPTS || '3'),
    },
    memory: {
      maxEventsPerUser: parseInt(env.ZCLAW_MAX_EVENTS || '10000'),
      embeddingModel: env.ZCLAW_EMBEDDING_MODEL || 'text-embedding-3-small',
    },
    log: {
      level: env.ZCLAW_LOG_LEVEL || 'info',
    },
    ...overrides,
  };

  _config = ConfigSchema.parse(raw);
  return _config;
}

export function getConfig(): ZClawConfig {
  if (!_config) {
    return loadConfig();
  }
  return _config;
}
