import {
  applyGeneratedSessionName,
  buildRunChatTurnParams,
  finalizeTurnCompletion,
  generateSessionName,
  getSessionMessageCount,
  needsNameGenerationCheck
} from "./chunk-QFSSKIQ3.js";
import {
  getEventStore
} from "./chunk-XKR3HCAL.js";
import "./chunk-FBGWG4N6.js";
import "./chunk-NONI4CRP.js";
import {
  createChatMessageMessage,
  createSessionRunningMessage
} from "./chunk-CEZNMLOO.js";
import "./chunk-FQLK5GL5.js";
import "./chunk-CGZHLM3K.js";
import {
  logger
} from "./chunk-K44MW7JJ.js";

// src/server/queue/processor.ts
var QueueProcessor = class {
  deps;
  unsubscribe = null;
  activeAgents = /* @__PURE__ */ new Map();
  constructor(deps) {
    this.deps = deps;
  }
  start() {
    if (this.unsubscribe) {
      logger.warn("QueueProcessor already started");
      return;
    }
    this.unsubscribe = this.deps.sessionManager.subscribe((event) => {
      if (event.type === "queue_added") {
        this.handleQueueAdded(event.sessionId);
      } else if (event.type === "running_changed" && !event.isRunning) {
        this.handleTurnDone(event.sessionId);
      }
    });
    logger.debug("QueueProcessor started");
  }
  stop() {
    if (this.unsubscribe) {
      this.unsubscribe();
      this.unsubscribe = null;
    }
    for (const controller of this.activeAgents.values()) {
      controller.abort();
    }
    this.activeAgents.clear();
    logger.debug("QueueProcessor stopped");
  }
  abortSession(sessionId) {
    const controller = this.activeAgents.get(sessionId);
    if (controller) {
      controller.abort();
      this.activeAgents.delete(sessionId);
      return true;
    }
    return false;
  }
  handleQueueAdded(sessionId) {
    const { sessionManager } = this.deps;
    const session = sessionManager.getSession(sessionId);
    if (!session) return;
    if (session.isRunning) {
      logger.debug("Session is running, not starting new turn", { sessionId });
      return;
    }
    if (!sessionManager.hasQueuedMessages(sessionId)) {
      logger.debug("No queued messages", { sessionId });
      return;
    }
    this.startTurn(sessionId);
  }
  handleTurnDone(sessionId) {
    logger.debug("Turn done, checking for more queued messages", { sessionId });
    const { sessionManager } = this.deps;
    if (!sessionManager.hasQueuedMessages(sessionId)) {
      logger.debug("No more queued messages", { sessionId });
      return;
    }
    this.startTurn(sessionId);
  }
  startTurn(sessionId) {
    const { sessionManager, broadcastForSession } = this.deps;
    logger.info("Starting turn from queue processor", { sessionId });
    const session = sessionManager.getSession(sessionId);
    if (!session || session.isRunning) {
      logger.warn("Cannot start turn: session not found or already running", { sessionId });
      return;
    }
    const queue = sessionManager.getQueueState(sessionId);
    if (queue.length === 0) {
      logger.warn("Cannot start turn: queue is empty", { sessionId });
      return;
    }
    const controller = new AbortController();
    this.activeAgents.set(sessionId, controller);
    sessionManager.setRunning(sessionId, true);
    broadcastForSession(sessionId, createSessionRunningMessage(true));
    const nextAsap = queue.find((m) => m.mode === "asap") ?? queue[0];
    if (nextAsap) {
      sessionManager.cancelQueuedMessage(sessionId, nextAsap.queueId);
      const userMessage = sessionManager.addMessage(sessionId, {
        role: "user",
        content: nextAsap.content,
        ...nextAsap.attachments ? { attachments: nextAsap.attachments } : {}
      });
      broadcastForSession(sessionId, createChatMessageMessage(userMessage));
      logger.debug("Added queued message to session", {
        sessionId,
        queueId: nextAsap.queueId,
        messageId: userMessage.id
      });
      const messageCount = this.getSessionMessageCount(sessionId);
      const currentSession = sessionManager.getSession(sessionId);
      if (currentSession && needsNameGenerationCheck(sessionId, currentSession.metadata.title, messageCount)) {
        const eventStore = getEventStore();
        generateSessionName({
          userMessage: nextAsap.content,
          llmClient: this.deps.getLLMClient(),
          signal: controller.signal
        }).then((result) => {
          logger.debug("Session name generation result (queue)", {
            sessionId,
            success: result.success,
            name: result.name,
            error: result.error
          });
          if (result.success && result.name) {
            applyGeneratedSessionName(sessionId, result.name, {
              sessionManager,
              eventStore,
              broadcastForSession
            });
          }
        }).catch((error) => {
          logger.error("Session name generation failed (queue)", {
            sessionId,
            error: error instanceof Error ? error.message : String(error)
          });
        });
      }
    }
    this.runTurn(sessionId, controller);
  }
  async runTurn(sessionId, controller) {
    const { sessionManager, getLLMClient, getActiveProvider, broadcastForSession, providerManager } = this.deps;
    const session = sessionManager.getSession(sessionId);
    if (session?.providerId && session.providerModel) {
      const currentActiveProviderId = providerManager.getActiveProviderId();
      const currentModel = providerManager.getCurrentModel();
      if (currentActiveProviderId !== session.providerId || currentModel !== session.providerModel) {
        logger.info("Switching to session provider", {
          sessionId,
          fromProvider: currentActiveProviderId,
          fromModel: currentModel,
          toProvider: session.providerId,
          toModel: session.providerModel
        });
        const result = await providerManager.activateProvider(session.providerId, { model: session.providerModel });
        if (!result.success) {
          logger.error("Failed to activate session provider", { sessionId, error: result.error });
        }
      }
    }
    const llmClient = getLLMClient();
    const provider = getActiveProvider?.();
    const statsIdentity = {
      providerId: provider?.id ?? `provider:${llmClient.getModel()}`,
      providerName: provider?.name ?? "Unknown Provider",
      backend: provider?.backend ?? llmClient.getBackend(),
      model: llmClient.getModel()
    };
    const { runChatTurn } = await import("./orchestrator-7ZXM4J22.js");
    const runChatTurnParams = buildRunChatTurnParams({
      sessionManager,
      sessionId,
      llmClient,
      statsIdentity,
      signal: controller.signal,
      onMessage: (msg) => broadcastForSession(sessionId, msg)
    });
    runChatTurn(runChatTurnParams).catch((error) => {
      if (error instanceof Error && error.message === "Aborted") {
        return;
      }
      logger.error("QueueProcessor turn error", { sessionId, error });
    }).finally(() => {
      this.activeAgents.delete(sessionId);
      try {
        const session2 = sessionManager.getSession(sessionId);
        if (!session2) {
          sessionManager.setRunning(sessionId, false);
          broadcastForSession(sessionId, createSessionRunningMessage(false));
          return;
        }
        const hasMore = sessionManager.hasQueuedMessages(sessionId);
        if (!hasMore) {
          finalizeTurnCompletion(sessionId, sessionManager, broadcastForSession);
          return;
        }
        this.startTurn(sessionId);
      } catch (error) {
        logger.error("Error in turn completion cleanup", {
          sessionId,
          error: error instanceof Error ? error.message : String(error)
        });
      }
    });
  }
  getSessionMessageCount(sessionId) {
    return getSessionMessageCount(sessionId);
  }
};
export {
  QueueProcessor
};
//# sourceMappingURL=processor-TKBJLQ2N.js.map