import { buildTextOrMarkdownMessage } from '../feishu/card-builder.js';

/**
 * WebhookWriter — 用于 delivery_mode='webhook' 的服务端执行模式
 * 实现与 WebSocketWriter 相同的接口（.send / .setSessionId / .getSessionId），
 * 捕获 Claude 的文本回复，在 claude-complete 时 POST 到 webhookUrl。
 */
export class WebhookWriter {
  constructor({ webhookUrl, cronId, cronExpr, prompt, userUuid, cwd }) {
    this.webhookUrl = webhookUrl;
    this.meta = { cronId, cronExpr, prompt };
    this.userUuid = userUuid;
    this.cwd = cwd;
    this.textBuffer = '';
    this.sessionId = null;
  }

  send(data) {
    try {
      const obj = typeof data === 'string' ? JSON.parse(data) : data;
      if (obj.type === 'claude-response') {
        const d = obj.data;
        if (d?.type === 'assistant' && Array.isArray(d.message?.content)) {
          // 非流式：完整 assistant 消息
          for (const block of d.message.content) {
            if (block.type === 'text') this.textBuffer += block.text;
          }
        } else if (d?.type === 'content_block_delta' && d.delta?.text) {
          // 流式：逐块 delta
          this.textBuffer += d.delta.text;
        }
      } else if (obj.type === 'claude-complete') {
        this._postWebhook();
      }
    } catch (_) {
      // 忽略 JSON 解析错误
    }
  }

  setSessionId(id) { this.sessionId = id; }
  getSessionId() { return this.sessionId; }

  async _postWebhook() {
    const feishu = buildTextOrMarkdownMessage(this.textBuffer);
    const parsedContent = JSON.parse(feishu.content);
    const feishuPayload = feishu.msgType === 'interactive'
      ? { msg_type: feishu.msgType, card: parsedContent }
      : { msg_type: feishu.msgType, content: parsedContent };
    const body = {
      cron_id: this.meta.cronId,
      cron_expr: this.meta.cronExpr,
      prompt: this.meta.prompt,
      fired_at: Date.now(),
      response: this.textBuffer,
      ...feishuPayload,
    };
    console.log(`[CronWebhook] POST body:`, JSON.stringify(body));

    const MAX_RETRIES = 3;
    let lastErr;
    for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
      try {
        const res = await fetch(this.webhookUrl, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify(body),
        });
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        console.log(`[CronWebhook] POST succeeded for task ${this.meta.cronId}, response length=${this.textBuffer.length}`);
        return;
      } catch (err) {
        lastErr = err;
        if (attempt < MAX_RETRIES) {
          const delay = attempt * 2000; // 2s, 4s
          console.warn(`[CronWebhook] POST failed for task ${this.meta.cronId} (attempt ${attempt}/${MAX_RETRIES}), retrying in ${delay}ms: ${err.message}`);
          await new Promise(r => setTimeout(r, delay));
        }
      }
    }
    console.error(`[CronWebhook] POST failed for task ${this.meta.cronId} after ${MAX_RETRIES} attempts:`, lastErr.message);
  }
}
