/**
 * 最小 AG-UI Agent 实现示例
 * 
 * 展示如何创建一个自定义 Agent，实现基本的事件流
 * 
 * 参考文档: modules/agents.md (行 132-197)
 */

import {
  AbstractAgent,
  RunAgent,
  RunAgentInput,
  EventType,
  BaseEvent,
} from "@ag-ui/client"
import { Observable } from "rxjs"

class MinimalAgent extends AbstractAgent {
  /**
   * 实现 run 方法，返回事件流
   */
  run(input: RunAgentInput): RunAgent {
    const { threadId, runId } = input

    return () =>
      new Observable<BaseEvent>((observer) => {
        // 1. 发送 RUN_STARTED 事件
        observer.next({
          type: EventType.RUN_STARTED,
          threadId,
          runId,
        })

        // 2. 发送文本消息
        const messageId = Date.now().toString()

        // 消息开始
        observer.next({
          type: EventType.TEXT_MESSAGE_START,
          messageId,
          role: "assistant",
        })

        // 消息内容（流式）
        observer.next({
          type: EventType.TEXT_MESSAGE_CONTENT,
          messageId,
          delta: "Hello! ",
        })

        observer.next({
          type: EventType.TEXT_MESSAGE_CONTENT,
          messageId,
          delta: "I'm a minimal AG-UI agent.",
        })

        // 消息结束
        observer.next({
          type: EventType.TEXT_MESSAGE_END,
          messageId,
        })

        // 3. 发送 RUN_FINISHED 事件
        observer.next({
          type: EventType.RUN_FINISHED,
          threadId,
          runId,
        })

        // 完成流
        observer.complete()
      })
  }
}

// 使用示例
const agent = new MinimalAgent({
  agentId: "minimal-agent",
  description: "A minimal AG-UI agent example",
})

// 运行 Agent 并订阅事件流
agent
  .runAgent({
    runId: "run_123",
    threadId: "thread_456",
    messages: [],
    tools: [],
    context: [],
  })
  .subscribe({
    next: (event) => {
      console.log(`[${event.type}]`, event)
    },
    error: (error) => console.error("Error:", error),
    complete: () => console.log("Agent run completed"),
  })

export { MinimalAgent }
