/**
 * Butler 应用入口 — 定时任务 + 多平台消息
 */
import { dispatch } from '@flue/runtime';
import { flue } from '@flue/runtime/routing';
import { Cron } from 'croner';
import { Hono } from 'hono';
import { readFileSync } from 'fs';
import { spawn } from 'child_process';
import { join } from 'path';
import { homedir } from 'os';
import jeevesAgent from './agents/jeeves';

const app = new Hono();
app.route('/', flue());

// ====== Playwright MCP (浏览器自动化) ======
// 行业标准: 配置在 .env → 启动时拉起 → 退出时自动清理
if (process.env.JEEVES_MCP_BROWSER === 'true') {
  const MCP_PORT = 8931;
  const mcpProcess = spawn('npx', ['@playwright/mcp@latest', '--port', String(MCP_PORT), '--headless'], {
    stdio: 'ignore',
    windowsHide: true,
    shell: true,
  });
  console.log(`[MCP] Playwright MCP 已启动 (port ${MCP_PORT})`);

  const cleanup = () => { try { mcpProcess.kill(); } catch {} };
  process.on('exit', cleanup);
  process.on('SIGINT', cleanup);
  process.on('SIGTERM', cleanup);
}

// ====== 定时任务 ======
const schedulesPath = join(homedir(), '.jeeves', 'schedules.yaml');
let schedules: any[] = [];
try {
  const content = readFileSync(schedulesPath, 'utf-8');
  let current: any = null;
  for (const line of content.split('\n')) {
    const t = line.trim();
    if (t.startsWith('#') || !t) continue;
    if (t.startsWith('- name:')) {
      if (current?.cron && current?.prompt) schedules.push(current);
      current = { name: t.slice(7).trim().replace(/['"]/g, '') };
    } else if (current && t.startsWith('cron:')) {
      current.cron = t.slice(5).trim().replace(/['"]/g, '');
    } else if (current && t.startsWith('prompt:')) {
      current.prompt = t.slice(7).trim().replace(/['"]/g, '');
    }
  }
  if (current?.cron && current?.prompt) schedules.push(current);
} catch {}

for (const task of schedules) {
  try {
    new Cron(task.cron, { protect: true, timezone: 'Asia/Shanghai' }, async () => {
      console.log(`[CRON] ${task.name}`);
      await dispatch(jeevesAgent, {
        id: `cron-${task.name.replace(/\s+/g, '-')}`,
        session: task.name,
        message: task.prompt,
      });
    });
    console.log(`[CRON] ${task.name} (${task.cron})`);
  } catch (e: any) {
    console.error(`[CRON] ${task.name} ERROR:`, e.message);
  }
}
console.log(`[CRON] 共 ${schedules.length} 个定时任务`);

// ====== Telegram Webhook (多平台消息) ======
const TELEGRAM_TOKEN = process.env.TELEGRAM_BOT_TOKEN;

if (TELEGRAM_TOKEN) {
  app.post('/webhooks/telegram', async (c) => {
    try {
      const body = await c.req.json();
      const msg = body?.message || body?.edited_message;
      if (!msg?.text) return c.text('ok');

      const chatId = String(msg.chat.id);
      const text = msg.text;

      // dispatch 到 butler agent 异步处理
      await dispatch(jeevesAgent, {
        id: `tg-${chatId}`,
        session: `tg-${chatId}`,
        message: text,
      });

      return c.text('ok');
    } catch (e: any) {
      console.error('[TG] webhook error:', e.message);
      return c.text('ok');
    }
  });
  console.log('[TG] Telegram webhook ready: /webhooks/telegram');
}

export default app;
