import blessed from "blessed";
import { EventEmitter } from "events";
class SubagentFleet extends EventEmitter {
  container;
  agentList;
  statsBox;
  agents;
  selectedAgent = null;
  constructor(container) {
    super();
    this.container = container;
    this.agents = /* @__PURE__ */ new Map();
    this.initializeUI();
  }
  initializeUI() {
    this.agentList = blessed.list({
      parent: this.container,
      top: 0,
      left: 0,
      width: "60%",
      height: "100%-3",
      style: {
        selected: {
          bg: "magenta",
          fg: "white",
          bold: true
        },
        item: {
          fg: "white"
        }
      },
      mouse: true,
      keys: true,
      vi: true,
      scrollable: true,
      tags: true
    });
    this.statsBox = blessed.box({
      parent: this.container,
      top: 0,
      right: 0,
      width: "40%",
      height: "100%-3",
      content: this.getFleetStats(),
      tags: true,
      scrollable: true,
      style: {
        fg: "white"
      }
    });
    const footer = blessed.box({
      parent: this.container,
      bottom: 0,
      left: 0,
      width: "100%",
      height: 3,
      content: "Fleet: 0 agents | Active: 0 | Idle: 0",
      tags: true,
      style: {
        fg: "white",
        bg: "black"
      }
    });
    this.agentList.on("select", (item, index) => {
      const agentId = Array.from(this.agents.keys())[index];
      this.selectAgent(agentId);
    });
    this.setupKeyboardShortcuts();
  }
  setupKeyboardShortcuts() {
    this.container.key(["t"], () => {
      if (this.selectedAgent) {
        this.terminateAgent(this.selectedAgent);
      }
    });
    this.container.key(["r"], () => {
      if (this.selectedAgent) {
        this.restartAgent(this.selectedAgent);
      }
    });
    this.container.key(["l"], () => {
      if (this.selectedAgent) {
        this.showAgentLogs(this.selectedAgent);
      }
    });
  }
  /**
   * Format agent item for display
   */
  formatAgentItem(agent) {
    const status = this.getStatusIcon(agent.status);
    const type = this.getAgentTypeIcon(agent.type);
    const successRate = Math.round(agent.successRate * 100);
    const rateColor = successRate >= 90 ? "green" : successRate >= 70 ? "yellow" : "red";
    let item = `${status} ${type} ${agent.type} (${agent.id.substring(0, 8)})
`;
    if (agent.currentTask) {
      const progress = Math.round(agent.currentTask.progress * 100);
      const elapsed = this.formatDuration(
        Date.now() - agent.currentTask.startTime
      );
      item += `   {cyan-fg}\u25B6 ${agent.currentTask.description.substring(0, 30)}...{/}
`;
      item += `   Progress: ${this.createProgressBar(agent.currentTask.progress)} ${progress}% (${elapsed})`;
    } else {
      item += `   Completed: ${agent.tasksCompleted} | Failed: ${agent.tasksFailed}
`;
      item += `   Success Rate: {${rateColor}-fg}${successRate}%{/} | Avg Time: ${this.formatDuration(agent.averageTime)}`;
    }
    if (agent.cpuUsage !== void 0 || agent.memoryUsage !== void 0) {
      item += "\n   ";
      if (agent.cpuUsage !== void 0) {
        const cpuColor = agent.cpuUsage > 80 ? "red" : agent.cpuUsage > 50 ? "yellow" : "green";
        item += `CPU: {${cpuColor}-fg}${Math.round(agent.cpuUsage)}%{/} `;
      }
      if (agent.memoryUsage !== void 0) {
        const memColor = agent.memoryUsage > 80 ? "red" : agent.memoryUsage > 50 ? "yellow" : "green";
        item += `MEM: {${memColor}-fg}${Math.round(agent.memoryUsage)}%{/} `;
      }
      if (agent.tokenUsage !== void 0) {
        item += `Tokens: ${this.formatTokens(agent.tokenUsage)}`;
      }
    }
    if (agent.lastError) {
      const errorAge = this.formatDuration(
        Date.now() - agent.lastError.timestamp
      );
      item += `
   {red-fg}\u26A0 Error ${errorAge} ago: ${agent.lastError.message.substring(0, 40)}{/}`;
    }
    return item;
  }
  getStatusIcon(status) {
    switch (status) {
      case "active":
        return "{green-fg}\u25CF{/}";
      case "idle":
        return "{cyan-fg}\u25CF{/}";
      case "error":
        return "{red-fg}\u25CF{/}";
      case "completed":
        return "{gray-fg}\u25CF{/}";
      default:
        return "{white-fg}\u25CB{/}";
    }
  }
  getAgentTypeIcon(type) {
    const icons = {
      analyzer: "\u{1F50D}",
      builder: "\u{1F528}",
      debugger: "\u{1F41B}",
      tester: "\u{1F9EA}",
      reviewer: "\u{1F441}\uFE0F",
      refactorer: "\u267B\uFE0F",
      documenter: "\u{1F4DD}",
      security: "\u{1F512}",
      performance: "\u26A1",
      general: "\u{1F916}"
    };
    return icons[type.toLowerCase()] || "\u{1F916}";
  }
  createProgressBar(progress) {
    const width = 10;
    const filled = Math.round(progress * width);
    const empty = width - filled;
    const color = progress >= 0.8 ? "green" : progress >= 0.5 ? "yellow" : "cyan";
    return `{${color}-fg}${"\u2588".repeat(filled)}{/}{gray-fg}${"\u2591".repeat(empty)}{/}`;
  }
  formatDuration(ms) {
    if (ms < 1e3) return `${ms}ms`;
    if (ms < 6e4) return `${Math.round(ms / 1e3)}s`;
    if (ms < 36e5) return `${Math.round(ms / 6e4)}m`;
    return `${Math.round(ms / 36e5)}h`;
  }
  formatTokens(tokens) {
    if (tokens < 1e3) return `${tokens}`;
    if (tokens < 1e6) return `${(tokens / 1e3).toFixed(1)}K`;
    return `${(tokens / 1e6).toFixed(1)}M`;
  }
  /**
   * Generate fleet statistics
   */
  getFleetStats() {
    const agents = Array.from(this.agents.values());
    if (agents.length === 0) {
      return "{gray-fg}No agents active{/}";
    }
    const stats = {
      total: agents.length,
      active: agents.filter((a) => a.status === "active").length,
      idle: agents.filter((a) => a.status === "idle").length,
      error: agents.filter((a) => a.status === "error").length,
      totalTasks: agents.reduce(
        (sum, a) => sum + a.tasksCompleted + a.tasksFailed,
        0
      ),
      successfulTasks: agents.reduce((sum, a) => sum + a.tasksCompleted, 0),
      failedTasks: agents.reduce((sum, a) => sum + a.tasksFailed, 0),
      avgSuccessRate: agents.reduce((sum, a) => sum + a.successRate, 0) / agents.length,
      totalTokens: agents.reduce((sum, a) => sum + (a.tokenUsage || 0), 0),
      avgCpu: agents.reduce((sum, a) => sum + (a.cpuUsage || 0), 0) / agents.length,
      avgMemory: agents.reduce((sum, a) => sum + (a.memoryUsage || 0), 0) / agents.length
    };
    const typeGroups = /* @__PURE__ */ new Map();
    agents.forEach((agent) => {
      typeGroups.set(agent.type, (typeGroups.get(agent.type) || 0) + 1);
    });
    let output = "{bold}Fleet Statistics{/}\n\n";
    output += "{bold}Status:{/}\n";
    output += `  Total: ${stats.total}
`;
    output += `  Active: {green-fg}${stats.active}{/}
`;
    output += `  Idle: {cyan-fg}${stats.idle}{/}
`;
    output += `  Error: {red-fg}${stats.error}{/}
`;
    output += "\n{bold}Performance:{/}\n";
    output += `  Tasks: ${stats.successfulTasks}/${stats.totalTasks}
`;
    const rateColor = stats.avgSuccessRate >= 0.9 ? "green" : stats.avgSuccessRate >= 0.7 ? "yellow" : "red";
    output += `  Success: {${rateColor}-fg}${Math.round(stats.avgSuccessRate * 100)}%{/}
`;
    output += `  Tokens: ${this.formatTokens(stats.totalTokens)}
`;
    output += "\n{bold}Resources:{/}\n";
    const cpuColor = stats.avgCpu > 80 ? "red" : stats.avgCpu > 50 ? "yellow" : "green";
    const memColor = stats.avgMemory > 80 ? "red" : stats.avgMemory > 50 ? "yellow" : "green";
    output += `  CPU: {${cpuColor}-fg}${Math.round(stats.avgCpu)}%{/}
`;
    output += `  Memory: {${memColor}-fg}${Math.round(stats.avgMemory)}%{/}
`;
    output += "\n{bold}Types:{/}\n";
    Array.from(typeGroups.entries()).sort((a, b) => b[1] - a[1]).forEach(([type, count]) => {
      const icon = this.getAgentTypeIcon(type);
      output += `  ${icon} ${type}: ${count}
`;
    });
    return output;
  }
  update(agents) {
    this.agents.clear();
    agents.forEach((agent) => {
      this.agents.set(agent.id, agent);
    });
    const items = agents.map((agent) => this.formatAgentItem(agent));
    this.agentList.setItems(items);
    this.statsBox.setContent(this.getFleetStats());
    const active = agents.filter((a) => a.status === "active").length;
    const idle = agents.filter((a) => a.status === "idle").length;
    const total = agents.length;
    const footer = this.container.children[2];
    if (footer) {
      footer.setContent(
        `{bold}Fleet:{/} ${total} agents | {bold}Active:{/} {green-fg}${active}{/} | {bold}Idle:{/} {cyan-fg}${idle}{/}`
      );
    }
    this.container.screen.render();
  }
  selectAgent(agentId) {
    this.selectedAgent = agentId;
    const agent = this.agents.get(agentId);
    if (agent) {
      this.emit("agent:selected", agent);
      this.showAgentDetails(agent);
    }
  }
  showAgentDetails(agent) {
    const details = blessed.box({
      parent: this.container.screen,
      top: "center",
      left: "center",
      width: "70%",
      height: "70%",
      content: this.formatAgentDetails(agent),
      tags: true,
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "magenta"
        }
      },
      scrollable: true,
      keys: true,
      vi: true,
      mouse: true,
      hidden: false,
      label: ` Agent: ${agent.type} (${agent.id}) `
    });
    details.key(["escape", "q"], () => {
      details.destroy();
      this.container.screen.render();
    });
    details.focus();
    this.container.screen.render();
  }
  formatAgentDetails(agent) {
    let details = `{bold}Agent ID:{/} ${agent.id}
`;
    details += `{bold}Type:{/} ${this.getAgentTypeIcon(agent.type)} ${agent.type}
`;
    details += `{bold}Status:{/} ${this.getStatusIcon(agent.status)} ${agent.status}
`;
    if (agent.currentTask) {
      details += `
{bold}Current Task:{/}
`;
      details += `  ID: ${agent.currentTask.id}
`;
      details += `  Description: ${agent.currentTask.description}
`;
      details += `  Progress: ${Math.round(agent.currentTask.progress * 100)}%
`;
      details += `  Started: ${new Date(agent.currentTask.startTime).toLocaleString()}
`;
      details += `  Elapsed: ${this.formatDuration(Date.now() - agent.currentTask.startTime)}
`;
    }
    details += `
{bold}Performance Metrics:{/}
`;
    details += `  Tasks Completed: ${agent.tasksCompleted}
`;
    details += `  Tasks Failed: ${agent.tasksFailed}
`;
    details += `  Success Rate: ${Math.round(agent.successRate * 100)}%
`;
    details += `  Average Time: ${this.formatDuration(agent.averageTime)}
`;
    if (agent.cpuUsage !== void 0 || agent.memoryUsage !== void 0 || agent.tokenUsage !== void 0) {
      details += `
{bold}Resource Usage:{/}
`;
      if (agent.cpuUsage !== void 0) {
        details += `  CPU: ${Math.round(agent.cpuUsage)}%
`;
      }
      if (agent.memoryUsage !== void 0) {
        details += `  Memory: ${Math.round(agent.memoryUsage)}%
`;
      }
      if (agent.tokenUsage !== void 0) {
        details += `  Tokens: ${this.formatTokens(agent.tokenUsage)}
`;
      }
    }
    if (agent.lastError) {
      details += `
{bold}Last Error:{/}
`;
      details += `  Message: ${agent.lastError.message}
`;
      details += `  Time: ${new Date(agent.lastError.timestamp).toLocaleString()}
`;
      details += `  Recoverable: ${agent.lastError.recoverable ? "Yes" : "No"}
`;
    }
    details += `
{gray-fg}[t] Terminate | [r] Restart | [l] View Logs{/}
`;
    return details;
  }
  terminateAgent(agentId) {
    this.emit("agent:terminate", { agentId });
    const agent = this.agents.get(agentId);
    if (agent) {
      agent.status = "completed";
      this.update(Array.from(this.agents.values()));
    }
  }
  restartAgent(agentId) {
    this.emit("agent:restart", { agentId });
    const agent = this.agents.get(agentId);
    if (agent) {
      agent.status = "idle";
      agent.lastError = void 0;
      this.update(Array.from(this.agents.values()));
    }
  }
  showAgentLogs(agentId) {
    this.emit("agent:logs", { agentId });
  }
  focus() {
    this.agentList.focus();
  }
  hasFocus() {
    return this.agentList === this.container.screen.focused;
  }
}
export {
  SubagentFleet
};
//# sourceMappingURL=subagent-fleet.js.map
