import blessed from "blessed";
import { EventEmitter } from "events";
class SessionMonitor extends EventEmitter {
  container;
  sessionList;
  sessions;
  selectedSession = null;
  constructor(container) {
    super();
    this.container = container;
    this.sessions = /* @__PURE__ */ new Map();
    this.initializeUI();
  }
  initializeUI() {
    this.sessionList = blessed.list({
      parent: this.container,
      top: 0,
      left: 0,
      width: "100%",
      height: "100%-3",
      style: {
        selected: {
          bg: "blue",
          fg: "white",
          bold: true
        },
        item: {
          fg: "cyan"
        }
      },
      mouse: true,
      keys: true,
      vi: true,
      scrollable: true,
      tags: true
    });
    const footer = blessed.box({
      parent: this.container,
      bottom: 0,
      left: 0,
      width: "100%",
      height: 3,
      content: "Active: 0 | Idle: 0 | Total: 0",
      tags: true,
      style: {
        fg: "white",
        bg: "black"
      }
    });
    this.sessionList.on("select", (item, index) => {
      const sessionId = Array.from(this.sessions.keys())[index];
      this.selectSession(sessionId);
    });
  }
  /**
   * Auto-tag session based on work context
   */
  autoTagSession(session) {
    const tags = [];
    if (session.recentActivities) {
      const files = session.recentActivities.filter((a) => a.type === "file_edit").map((a) => a.data?.path || "");
      if (files.some((f) => f.includes("test"))) tags.push("testing");
      if (files.some((f) => f.includes(".tsx") || f.includes(".jsx")))
        tags.push("frontend");
      if (files.some((f) => f.includes("api") || f.includes("server")))
        tags.push("backend");
      if (files.some((f) => f.includes("db") || f.includes("migration")))
        tags.push("database");
      const commands = session.recentActivities.filter((a) => a.type === "command").map((a) => a.data?.command || "");
      if (commands.some((c) => c.includes("npm test") || c.includes("jest")))
        tags.push("testing");
      if (commands.some((c) => c.includes("git"))) tags.push("git-ops");
      if (commands.some((c) => c.includes("deploy"))) tags.push("deployment");
      if (commands.some((c) => c.includes("debug"))) tags.push("debugging");
    }
    if (session.linearTask) {
      tags.push(`linear:${session.linearTask.identifier}`);
      if (session.linearTask.labels) {
        tags.push(
          ...session.linearTask.labels.map((l) => l.toLowerCase())
        );
      }
    }
    if (session.gitBranch) {
      const branch = session.gitBranch;
      if (branch.includes("feature/")) tags.push("feature");
      if (branch.includes("fix/") || branch.includes("bugfix/"))
        tags.push("bugfix");
      if (branch.includes("refactor/")) tags.push("refactor");
      if (branch.includes("docs/")) tags.push("documentation");
    }
    if (session.agentType) {
      tags.push(`agent:${session.agentType}`);
    }
    return tags.length > 0 ? tags.join(" \u2022 ") : "general";
  }
  /**
   * Generate session display name with context
   */
  generateSessionName(session) {
    const autoTags = this.autoTagSession(session);
    const timestamp = new Date(session.startTime).toLocaleTimeString();
    let primaryActivity = "Session";
    if (session.linearTask) {
      primaryActivity = session.linearTask.title || session.linearTask.identifier;
    } else if (session.gitBranch && session.gitBranch !== "main" && session.gitBranch !== "master") {
      primaryActivity = session.gitBranch.split("/").pop() || session.gitBranch;
    } else if (session.primaryFile) {
      primaryActivity = session.primaryFile.split("/").pop() || "Code";
    }
    return `${primaryActivity} [${autoTags}] - ${timestamp}`;
  }
  /**
   * Format session item for display
   */
  formatSessionItem(session) {
    const status = this.getSessionStatus(session);
    const statusIcon = this.getStatusIcon(status);
    const name = this.generateSessionName(session);
    const metrics = this.getSessionMetrics(session);
    const contextUsage = Math.round(session.contextUsage * 100);
    const contextColor = contextUsage > 80 ? "red" : contextUsage > 60 ? "yellow" : "green";
    return `${statusIcon} ${name}
   {gray-fg}Tokens: ${metrics.tokens} | Context: {${contextColor}-fg}${contextUsage}%{/} | Duration: ${metrics.duration}{/}`;
  }
  getSessionStatus(session) {
    if (session.error) return "error";
    if (session.completed) return "completed";
    const now = Date.now();
    const lastActivity = session.lastActivity || session.startTime;
    const idleTime = now - lastActivity;
    if (idleTime > 5 * 60 * 1e3) return "idle";
    return "active";
  }
  getStatusIcon(status) {
    switch (status) {
      case "active":
        return "{green-fg}\u25CF{/}";
      case "idle":
        return "{yellow-fg}\u25CF{/}";
      case "completed":
        return "{gray-fg}\u25CF{/}";
      case "error":
        return "{red-fg}\u25CF{/}";
      default:
        return "{white-fg}\u25CB{/}";
    }
  }
  getSessionMetrics(session) {
    const now = Date.now();
    const duration = now - session.startTime;
    const hours = Math.floor(duration / (1e3 * 60 * 60));
    const minutes = Math.floor(duration % (1e3 * 60 * 60) / (1e3 * 60));
    return {
      tokens: session.totalTokens || 0,
      duration: hours > 0 ? `${hours}h ${minutes}m` : `${minutes}m`,
      filesEdited: session.filesEdited?.length || 0,
      commandsRun: session.commandsRun || 0,
      errorsEncountered: session.errors?.length || 0
    };
  }
  update(sessions) {
    this.sessions.clear();
    sessions.forEach((session) => {
      this.sessions.set(session.id, session);
    });
    const items = sessions.map(
      (session) => this.formatSessionItem(session)
    );
    this.sessionList.setItems(items);
    const active = sessions.filter(
      (s) => this.getSessionStatus(s) === "active"
    ).length;
    const idle = sessions.filter(
      (s) => this.getSessionStatus(s) === "idle"
    ).length;
    const total = sessions.length;
    const footer = this.container.children[1];
    if (footer) {
      footer.setContent(
        `{bold}Active:{/} {green-fg}${active}{/} | {bold}Idle:{/} {yellow-fg}${idle}{/} | {bold}Total:{/} ${total}`
      );
    }
    this.container.screen.render();
  }
  selectSession(sessionId) {
    this.selectedSession = sessionId;
    const session = this.sessions.get(sessionId);
    if (session) {
      this.emit("session:selected", session);
      this.showSessionDetails(session);
    }
  }
  showSessionDetails(session) {
    const details = blessed.box({
      parent: this.container.screen,
      top: "center",
      left: "center",
      width: "80%",
      height: "80%",
      content: this.formatSessionDetails(session),
      tags: true,
      border: {
        type: "line"
      },
      style: {
        border: {
          fg: "cyan"
        }
      },
      scrollable: true,
      keys: true,
      vi: true,
      mouse: true,
      hidden: false,
      label: ` Session: ${this.generateSessionName(session)} `
    });
    details.key(["escape", "q"], () => {
      details.destroy();
      this.container.screen.render();
    });
    details.focus();
    this.container.screen.render();
  }
  formatSessionDetails(session) {
    const metrics = this.getSessionMetrics(session);
    const status = this.getSessionStatus(session);
    const tags = this.autoTagSession(session);
    let details = `{bold}Session ID:{/} ${session.id}
`;
    details += `{bold}Status:{/} ${status}
`;
    details += `{bold}Tags:{/} ${tags}
`;
    details += `{bold}Started:{/} ${new Date(session.startTime).toLocaleString()}
`;
    if (session.lastActivity) {
      details += `{bold}Last Activity:{/} ${new Date(session.lastActivity).toLocaleString()}
`;
    }
    details += `
{bold}Metrics:{/}
`;
    details += `  Tokens Used: ${metrics.tokens}
`;
    details += `  Context Usage: ${Math.round(session.contextUsage * 100)}%
`;
    details += `  Duration: ${metrics.duration}
`;
    details += `  Files Edited: ${metrics.filesEdited}
`;
    details += `  Commands Run: ${metrics.commandsRun}
`;
    details += `  Errors: ${metrics.errorsEncountered}
`;
    if (session.linearTask) {
      details += `
{bold}Linear Task:{/}
`;
      details += `  ID: ${session.linearTask.identifier}
`;
      details += `  Title: ${session.linearTask.title}
`;
      details += `  State: ${session.linearTask.state}
`;
    }
    if (session.gitBranch) {
      details += `
{bold}Git:{/}
`;
      details += `  Branch: ${session.gitBranch}
`;
      if (session.lastCommit) {
        details += `  Last Commit: ${session.lastCommit}
`;
      }
    }
    if (session.recentActivities && session.recentActivities.length > 0) {
      details += `
{bold}Recent Activities:{/}
`;
      session.recentActivities.slice(-10).forEach((activity) => {
        details += `  ${new Date(activity.timestamp).toLocaleTimeString()} - ${activity.type}: ${activity.description}
`;
      });
    }
    return details;
  }
  focus() {
    this.sessionList.focus();
  }
  hasFocus() {
    return this.sessionList === this.container.screen.focused;
  }
}
export {
  SessionMonitor
};
//# sourceMappingURL=session-monitor.js.map
