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

/**
 * FeishuWriter — 用于 channel='feishu' 的服务端执行模式
 * 实现与 WebhookWriter 相同的接口（.send / .setSessionId / .getSessionId），
 * 捕获 Claude 的文本回复，在 claude-complete 时分块发送到飞书。
 */
export class FeishuWriter {
  constructor({ feishuOpenId, chatId, larkClient, cronId }) {
    this.larkClient = larkClient;
    this.cronId = cronId;
    // 优先用 chat_id（群聊/单聊会话 ID），回退 open_id（用户 ID）
    this._target = chatId || feishuOpenId;
    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._sendToFeishu();
      } else if (obj.type === 'claude-error') {
        console.error(`[CronFeishu] Task ${this.cronId} error:`, obj.error);
      }
    } catch (_) {
      // 忽略 JSON 解析错误
    }
  }

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

  async _sendToFeishu() {
    const text = this.textBuffer.trim();
    if (!text) {
      console.log(`[CronFeishu] Task ${this.cronId} completed with empty response, skipping send`);
      return;
    }
    const chunks = splitMessage(text, 4000);
    const MAX_RETRIES = 3;
    for (let i = 0; i < chunks.length; i++) {
      const chunk = chunks[i];
      let lastErr;
      for (let attempt = 1; attempt <= MAX_RETRIES; attempt++) {
        try {
          await this.larkClient.sendTextToTarget(this._target, chunk);
          lastErr = null;
          break;
        } catch (err) {
          lastErr = err;
          if (attempt < MAX_RETRIES) {
            const delay = attempt * 2000; // 2s, 4s
            console.warn(`[CronFeishu] Task ${this.cronId} chunk ${i + 1}/${chunks.length} send failed (attempt ${attempt}/${MAX_RETRIES}), retrying in ${delay}ms: ${err.message}`);
            await new Promise(r => setTimeout(r, delay));
          }
        }
      }
      if (lastErr) {
        console.error(`[CronFeishu] Send failed for task ${this.cronId} chunk ${i + 1}/${chunks.length} after ${MAX_RETRIES} attempts:`, lastErr.message);
      }
    }
    console.log(`[CronFeishu] Task ${this.cronId} sent ${chunks.length} chunk(s) to ${this._target}`);
  }
}
