/**
 * 默认流式渲染器（Telegram / Discord / Weixin）— 从 bridge-manager 的默认分支迁入（C-2）。
 *
 * 对应原 bridge 行：
 *   onTyping = 559（微信 !supportsMessageEditing）/ 592-594（默认）
 *   onDraft  = 647-668（🔥 无 throttle，只用 isUnchanged）
 *   onFinal  = 715-744（draftMsgId edit / else deliverPlatformFinal）
 *   abort    = 791-796（删 draft）
 *   delivered = !!draftMessageId（行 776 的 draftMessageId 项）
 */

import type { StreamRenderer, StreamRenderContext } from './stream-renderer'
import { DraftThrottle } from './stream-renderer'

export class EditDraftRenderer implements StreamRenderer {
  private draftMessageId?: string
  /** 仅用 isUnchanged，不用 shouldThrottle（默认 edit-draft 路径无 throttle）。 */
  private readonly draft = new DraftThrottle()

  constructor(private readonly ctx: StreamRenderContext) {}

  get delivered(): boolean {
    return !!this.draftMessageId
  }

  async onTyping(): Promise<void> {
    // 行 559 / 592-594：typing indicator
    await this.ctx.delivery.deliver(this.ctx.adapter, this.ctx.chatId, '', { isTypingIndicator: true })
  }

  async onDraft(partialText: string): Promise<void> {
    // 行 648：不支持编辑的平台跳过 draft
    if (!this.ctx.adapter.supportsMessageEditing) return
    // 行 653：文本未变跳过（注意：无 throttle — 地雷2）
    if (this.draft.isUnchanged(partialText)) return

    if (this.draftMessageId) {
      // 行 656-660：编辑现有草稿
      await this.ctx.delivery.deliver(this.ctx.adapter, this.ctx.chatId, partialText + ' ▌', {
        editMessageId: this.draftMessageId,
      })
    } else {
      // 行 662-667：发送首条草稿
      const msgId = await this.ctx.delivery.deliver(this.ctx.adapter, this.ctx.chatId, partialText + ' ▌')
      if (msgId) this.draftMessageId = msgId
    }
  }

  async onFinal(text: string): Promise<void> {
    if (this.draftMessageId) {
      // 行 716-725：编辑草稿为最终文本
      const editResult = await this.ctx.delivery.deliver(this.ctx.adapter, this.ctx.chatId, text, {
        editMessageId: this.draftMessageId,
      })
      // edit 失败（返回不同 ID）→ 删旧 draft 防重复
      if (editResult && editResult !== this.draftMessageId) {
        await this.ctx.delivery.deliver(this.ctx.adapter, this.ctx.chatId, '', { deleteMessageId: this.draftMessageId })
      }
    } else {
      // 行 741-743：平台原生最终投递
      await this.ctx.deliverPlatformFinal(text)
    }
  }

  async abort(_reason: 'abort' | 'error', _errorMsg: string): Promise<void> {
    // 行 791-796：清理草稿
    if (this.draftMessageId) {
      await this.ctx.delivery.deliver(this.ctx.adapter, this.ctx.chatId, '', {
        deleteMessageId: this.draftMessageId,
      })
    }
  }
}
