// 多 Agent 协作系统 - Agent 基类
import type { AgentType, AgentConfig, AgentInfo, AgentTask, AgentResult, AgentMessage, AgentStatus } from './types';
import type { MessageBus } from './message-bus';
import type { AIManager } from '../ai/manager';
import { generateId } from '../../utils/id';
import { createLogger, type Logger } from '../../utils/logger';

export abstract class BaseAgent {
  readonly id: string;
  readonly type: AgentType;
  readonly name: string;
  protected status: AgentStatus = 'idle';
  protected config: AgentConfig;
  protected messageBus: MessageBus;
  protected ai: AIManager;
  protected log: Logger;
  protected currentTaskId?: string;
  protected createdAt: Date = new Date();

  constructor(
    type: AgentType,
    config: AgentConfig,
    messageBus: MessageBus,
    ai: AIManager,
  ) {
    this.id = generateId('agent');
    this.type = type;
    this.name = config.name || `${type}-agent`;
    this.config = config;
    this.messageBus = messageBus;
    this.ai = ai;
    this.log = createLogger(`Agent:${this.name}`);

    // 订阅消息
    this.messageBus.subscribe(this.id, (msg) => this.handleMessage(msg));

    this.log.info(`Agent created: ${this.id}`);
  }

  getInfo(): AgentInfo {
    return {
      id: this.id,
      type: this.type,
      name: this.name,
      status: this.status,
      capabilities: this.getCapabilities(),
      currentTaskId: this.currentTaskId,
      createdAt: this.createdAt,
    };
  }

  async execute(task: AgentTask): Promise<AgentResult> {
    this.status = 'busy';
    this.currentTaskId = task.id;
    const startTime = Date.now();

    this.log.info(`Executing task: ${task.id} - ${task.description}`);

    // 通知开始执行
    await this.messageBus.send({
      from: this.id,
      to: '*',
      type: 'status',
      payload: { taskId: task.id, status: 'running' },
    });

    try {
      const data = await this.run(task);
      const result: AgentResult = {
        taskId: task.id,
        agentId: this.id,
        success: true,
        data,
        duration: Date.now() - startTime,
      };

      // 通知完成
      await this.messageBus.send({
        from: this.id,
        to: '*',
        type: 'result',
        payload: result,
      });

      this.status = 'idle';
      this.currentTaskId = undefined;
      this.log.info(`Task completed: ${task.id} (${result.duration}ms)`);
      return result;

    } catch (error: any) {
      const result: AgentResult = {
        taskId: task.id,
        agentId: this.id,
        success: false,
        error: error.message,
        duration: Date.now() - startTime,
      };

      await this.messageBus.send({
        from: this.id,
        to: '*',
        type: 'error',
        payload: result,
      });

      this.status = 'error';
      this.currentTaskId = undefined;
      this.log.error(`Task failed: ${task.id} - ${error.message}`);
      return result;
    }
  }

  async terminate(): Promise<void> {
    this.status = 'terminated';
    this.messageBus.unsubscribe(this.id);
    this.log.info(`Agent terminated: ${this.id}`);
  }

  // 子类必须实现
  protected abstract run(task: AgentTask): Promise<any>;
  protected abstract getCapabilities(): string[];

  protected async handleMessage(message: AgentMessage): Promise<void> {
    this.log.debug(`Received message from ${message.from}: ${message.type}`);
  }
}
