import { v4 as uuidv4 } from 'uuid';
import type { AgentConfig } from '../types/index.js';
import type { AgentExecutionContext, AgentInfo } from './types.js';
import { AgentExecutor } from './executor.js';
import { ToolRegistry } from '../tools/registry.js';

/**
 * 后台 Agent 状态
 */
export type BackgroundAgentStatus = 'running' | 'completed' | 'failed';

/**
 * 后台 Agent 信息
 */
export interface BackgroundAgent {
  /** Agent 唯一 ID */
  id: string;
  /** Agent 类型名称 */
  agentName: string;
  /** 任务描述 */
  description: string;
  /** 执行状态 */
  status: BackgroundAgentStatus;
  /** 任务提示词 */
  prompt: string;
  /** 开始时间 */
  startedAt: Date;
  /** 完成时间 */
  completedAt?: Date;
  /** 执行结果 */
  result?: string;
  /** 错误信息 */
  error?: string;
  /** 执行步数 */
  steps?: number;
}

/**
 * Agent 管理器
 * 负责管理后台 Agent 的生命周期
 */
export class AgentManager {
  private backgroundAgents = new Map<string, BackgroundAgent>();
  private completionCallbacks = new Map<string, Array<() => void>>();

  /**
   * 启动后台 Agent
   */
  async runInBackground(
    agentInfo: AgentInfo,
    description: string,
    prompt: string,
    baseConfig: AgentConfig,
    toolRegistry: ToolRegistry,
    context: AgentExecutionContext
  ): Promise<string> {
    const agentId = uuidv4().substring(0, 8); // 短 ID

    // 创建后台 Agent 记录
    this.backgroundAgents.set(agentId, {
      id: agentId,
      agentName: agentInfo.name,
      description,
      status: 'running',
      prompt,
      startedAt: new Date(),
    });

    // 异步执行，不等待结果
    this.executeAsync(agentId, agentInfo, prompt, baseConfig, toolRegistry, context);

    return agentId;
  }

  /**
   * 异步执行 Agent 任务
   */
  private async executeAsync(
    agentId: string,
    agentInfo: AgentInfo,
    prompt: string,
    baseConfig: AgentConfig,
    toolRegistry: ToolRegistry,
    context: AgentExecutionContext
  ): Promise<void> {
    try {
      const executor = new AgentExecutor(agentInfo, baseConfig, toolRegistry);
      const result = await executor.execute(prompt, {
        ...context,
        onStream: undefined, // 后台运行不使用流式输出
      });

      // 更新状态为完成
      const agent = this.backgroundAgents.get(agentId);
      if (agent) {
        agent.status = result.success ? 'completed' : 'failed';
        agent.completedAt = new Date();
        agent.result = result.text;
        agent.steps = result.steps;
        if (!result.success) {
          agent.error = result.error;
        }
      }
    } catch (error) {
      // 更新状态为失败
      const agent = this.backgroundAgents.get(agentId);
      if (agent) {
        agent.status = 'failed';
        agent.completedAt = new Date();
        agent.error = error instanceof Error ? error.message : String(error);
      }
    }

    // 触发等待回调
    this.notifyCompletion(agentId);
  }

  /**
   * 获取后台 Agent 状态
   */
  getAgent(agentId: string): BackgroundAgent | null {
    return this.backgroundAgents.get(agentId) || null;
  }

  /**
   * 获取 Agent 输出（支持阻塞等待）
   */
  async getAgentOutput(
    agentId: string,
    block: boolean = true,
    timeoutSeconds: number = 150
  ): Promise<BackgroundAgent | null> {
    const agent = this.backgroundAgents.get(agentId);
    if (!agent) {
      return null;
    }

    // 如果已完成或不需要阻塞，直接返回
    if (agent.status !== 'running' || !block) {
      return agent;
    }

    // 阻塞等待完成
    return this.waitForCompletion(agentId, timeoutSeconds);
  }

  /**
   * 等待 Agent 完成
   */
  private waitForCompletion(
    agentId: string,
    timeoutSeconds: number
  ): Promise<BackgroundAgent | null> {
    return new Promise((resolve) => {
      const agent = this.backgroundAgents.get(agentId);
      if (!agent || agent.status !== 'running') {
        resolve(agent || null);
        return;
      }

      // 设置超时
      const timeoutId = setTimeout(() => {
        // 移除回调
        const callbacks = this.completionCallbacks.get(agentId);
        if (callbacks) {
          const index = callbacks.indexOf(callback);
          if (index > -1) {
            callbacks.splice(index, 1);
          }
        }
        resolve(this.backgroundAgents.get(agentId) || null);
      }, timeoutSeconds * 1000);

      // 注册完成回调
      const callback = () => {
        clearTimeout(timeoutId);
        resolve(this.backgroundAgents.get(agentId) || null);
      };

      if (!this.completionCallbacks.has(agentId)) {
        this.completionCallbacks.set(agentId, []);
      }
      this.completionCallbacks.get(agentId)!.push(callback);
    });
  }

  /**
   * 通知等待者任务已完成
   */
  private notifyCompletion(agentId: string): void {
    const callbacks = this.completionCallbacks.get(agentId);
    if (callbacks) {
      for (const callback of callbacks) {
        callback();
      }
      this.completionCallbacks.delete(agentId);
    }
  }

  /**
   * 列出所有后台 Agent
   */
  listAgents(): BackgroundAgent[] {
    return Array.from(this.backgroundAgents.values());
  }

  /**
   * 列出运行中的 Agent
   */
  listRunningAgents(): BackgroundAgent[] {
    return this.listAgents().filter((a) => a.status === 'running');
  }

  /**
   * 清理已完成的 Agent 记录
   */
  cleanup(maxAge: number = 3600000): void {
    const now = Date.now();
    for (const [id, agent] of this.backgroundAgents) {
      if (
        agent.status !== 'running' &&
        agent.completedAt &&
        now - agent.completedAt.getTime() > maxAge
      ) {
        this.backgroundAgents.delete(id);
      }
    }
  }
}

// 单例实例
let agentManager: AgentManager | null = null;

/**
 * 获取 AgentManager 单例
 */
export function getAgentManager(): AgentManager {
  if (!agentManager) {
    agentManager = new AgentManager();
  }
  return agentManager;
}

/**
 * 重置 AgentManager（测试用）
 */
export function resetAgentManager(): void {
  agentManager = null;
}
