/**
 * server/services/feishu/index.js — 飞书服务入口
 *
 * 读取环境变量，初始化 LarkClient + FeishuEngine，
 * 对外暴露 startFeishuService() / stopFeishuService()。
 *
 * 必需环境变量：
 *   FEISHU_APP_ID
 *   FEISHU_APP_SECRET
 *
 * 可选（语音转文字）：
 *   WHISPER_API_KEY  WHISPER_BASE_URL  WHISPER_MODEL  WHISPER_LANGUAGE
 */

import { LarkClient } from './lark-client.js';
import { FeishuEngine } from './feishu-engine.js';
import { checkFfmpeg } from './speech.js';

let larkClientInstance = null;

/**
 * 启动飞书服务
 * 由 server/index.js 在服务器启动时调用（仅当 FEISHU_APP_ID 和 FEISHU_APP_SECRET 已配置）
 */
async function startFeishuService() {
  const appId     = process.env.FEISHU_APP_ID;
  const appSecret = process.env.FEISHU_APP_SECRET;

  if (!appId || !appSecret) {
    console.log('[Feishu] Skipped: FEISHU_APP_ID or FEISHU_APP_SECRET not set');
    return null;
  }

  // 检查可选依赖
  const hasFfmpeg = await checkFfmpeg();
  if (!hasFfmpeg) {
    console.warn('[Feishu] ffmpeg not found — voice messages will not be transcribed');
  }

  const hasWhisper = !!(process.env.WHISPER_API_KEY || process.env.OPENAI_API_KEY);
  if (!hasWhisper) {
    console.warn('[Feishu] WHISPER_API_KEY not set — voice messages will not be transcribed');
  }

  try {
    // Engine 先创建（LarkClient 需要引用它）
    // LarkClient 构造时需要 engine，engine 构造时需要 larkClient
    // 用延迟注入：先 new engine(null)，再注入 larkClient
    const engine = new FeishuEngine(null);
    const client = new LarkClient(appId, appSecret, engine);
    engine.larkClient = client;
    engine.commandHandler.larkClient = client;

    await client.start();
    larkClientInstance = client;

    console.log('[Feishu] Service started successfully');
    return client;
  } catch (err) {
    console.error('[Feishu] Failed to start service:', err.message);
    return null;
  }
}

function getLarkClient() { return larkClientInstance; }

export { startFeishuService, getLarkClient };
