import { logger } from '../utils/logger.js';
import fs from 'fs-extra';
import path from 'path';

export async function initConfig() {
  const configPath = path.join(process.cwd(), '.zcode.config.json');
  
  const defaultConfig = {
    api: {
      provider: 'zai',
      baseUrl: process.env.GLM_BASE_URL || 'https://api.z.ai/api/coding/paas/v4',
      apiKey: process.env.ZAI_API_KEY || '',
      models: {
        default: 'glm-5.1',
        fast: 'GLM-5-Turbo',
        opus: 'glm-5.1',
      }
    },
    telegram: {
      enabled: true,
      botToken: process.env.TELEGRAM_BOT_TOKEN || '',
      allowedUsers: process.env.TELEGRAM_ALLOWED_USERS ? 
        process.env.TELEGRAM_ALLOWED_USERS.split(',').map(u => u.trim()) : [],
      webhookUrl: process.env.ZCODE_WEBHOOK_URL || '',
    },
    tools: {
      bash: true,
      fileEdit: true,
      webSearch: true,
      git: true,
      mcp: true,
    },
    skills: {
      enabled: true,
      autoLoad: true,
    },
    agents: {
      enabled: true,
      maxConcurrent: 3,
    },
    logging: {
      level: process.env.LOG_LEVEL || 'info',
      file: path.join(process.cwd(), 'logs/zcode.log'),
    },
  };

  // Load existing config or create default
  let config;
  if (await fs.pathExists(configPath)) {
    config = await fs.readJson(configPath);
    logger.info('✓ Loaded existing config');
  } else {
    config = defaultConfig;
    await fs.writeJson(configPath, config, { spaces: 2 });
    logger.info('✓ Created default config');
  }

  return config;
}
