import { z } from 'zod';
import { config as loadEnv } from 'dotenv';

// Load .env file
loadEnv();

/**
 * Configuration schema with Zod validation
 */
export const ConfigSchema = z.object({
  // Server
  host: z.string().default('127.0.0.1'),
  port: z.coerce.number().default(8765),

  // Repository
  repoRoot: z.string().optional(),

  // LLM Settings
  defaultModel: z.string().default('claude-sonnet-4-20250514'),
  maxIterations: z.coerce.number().default(100),
  maxTokens: z.coerce.number().default(16384),

  // API Keys (loaded from environment)
  anthropicApiKey: z.string().optional(),
  openaiApiKey: z.string().optional(),
  fireworksApiKey: z.string().optional(),

  // Features
  enableSwarm: z.coerce.boolean().default(false),
  enableEmbeddings: z.coerce.boolean().default(false),

  // Logging
  logLevel: z.enum(['trace', 'debug', 'info', 'warn', 'error', 'fatal']).default('info'),
});

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

/**
 * Load configuration from environment variables and optional overrides
 *
 * Environment variables use EMDASH_ prefix:
 * - EMDASH_HOST, EMDASH_PORT, EMDASH_DEFAULT_MODEL, etc.
 * - API keys: ANTHROPIC_API_KEY, OPENAI_API_KEY, FIREWORKS_API_KEY
 */
export function loadConfig(overrides?: Partial<Config>): Config {
  const env = process.env;

  const rawConfig = {
    host: env.EMDASH_HOST,
    port: env.EMDASH_PORT,
    repoRoot: env.EMDASH_REPO_ROOT,
    defaultModel: env.EMDASH_DEFAULT_MODEL,
    maxIterations: env.EMDASH_MAX_ITERATIONS,
    maxTokens: env.EMDASH_MAX_TOKENS,
    anthropicApiKey: env.ANTHROPIC_API_KEY,
    openaiApiKey: env.OPENAI_API_KEY,
    fireworksApiKey: env.FIREWORKS_API_KEY,
    enableSwarm: env.EMDASH_ENABLE_SWARM,
    enableEmbeddings: env.EMDASH_ENABLE_EMBEDDINGS,
    logLevel: env.EMDASH_LOG_LEVEL ?? env.LOG_LEVEL,
    ...overrides,
  };

  // Remove undefined values before parsing
  const cleanConfig = Object.fromEntries(
    Object.entries(rawConfig).filter(([, v]) => v !== undefined)
  );

  return ConfigSchema.parse(cleanConfig);
}
