import { UuidSchema } from './chunk-TVTSASST.js';
import { z } from 'zod';

// src/hooks/sessions/mergeSessionMessages.ts
function canonicalize(value) {
  if (Array.isArray(value)) {
    return value.map(canonicalize);
  }
  if (value && typeof value === "object") {
    const source = value;
    return Object.keys(source).sort().reduce((acc, key) => {
      acc[key] = canonicalize(source[key]);
      return acc;
    }, {});
  }
  return value;
}
function stableStringify(value) {
  return JSON.stringify(canonicalize(value));
}
function mergeSessionMessages(historyMessages, liveMessages) {
  const messageMap = /* @__PURE__ */ new Map();
  for (const message of historyMessages) {
    messageMap.set(message.id, message);
  }
  for (const message of liveMessages) {
    if (!message.id.startsWith("temp-")) {
      messageMap.set(message.id, message);
      continue;
    }
    const alreadyPersisted = Array.from(messageMap.values()).some((existing) => {
      if (existing.role !== message.role) return false;
      if (existing.messageType !== message.messageType) return false;
      if (message.metadata && existing.metadata) {
        return stableStringify(existing.metadata) === stableStringify(message.metadata);
      }
      return existing.text === message.text;
    });
    if (!alreadyPersisted) {
      messageMap.set(message.id, message);
    }
  }
  return Array.from(messageMap.values()).sort((a, b) => {
    if (a.turnNumber !== b.turnNumber) return a.turnNumber - b.turnNumber;
    return (a.messageIndex ?? 0) - (b.messageIndex ?? 0);
  });
}
var SessionIdParamSchema = z.object({
  sessionId: UuidSchema
}).strict();
var ExecutionIdParamsSchema = z.object({
  sessionId: UuidSchema,
  executionId: UuidSchema
}).strict();
var CreateSessionSchema = z.object({
  resourceId: z.string().min(1).max(100),
  userId: UuidSchema.optional(),
  metadata: z.any().optional()
}).strict();
z.object({
  input: z.unknown().refine(
    (val) => {
      let text;
      if (typeof val === "string") {
        text = val;
      } else if (val && typeof val === "object" && "message" in val) {
        text = String(val.message);
      } else {
        text = JSON.stringify(val);
      }
      return text.length > 0 && text.length <= 1e5;
    },
    { message: "Input must be between 1 and 100,000 characters" }
  ),
  metadata: z.any().optional()
}).strict();
z.object({
  userId: UuidSchema.optional(),
  resourceId: z.string().optional(),
  limit: z.coerce.number().int().min(1).max(100).default(20)
}).strict();
z.object({
  limit: z.coerce.number().int().min(1).max(100).default(100),
  cursor: z.coerce.number().int().min(0).optional()
}).strict();
var WebSocketSessionTurnSchema = z.object({
  type: z.literal("session:turn"),
  input: z.unknown().refine(
    (val) => {
      let text;
      if (typeof val === "string") {
        text = val;
      } else if (val && typeof val === "object" && "message" in val) {
        text = String(val.message);
      } else {
        text = JSON.stringify(val) || "";
      }
      return text && text.length > 0 && text.length <= 1e5;
    },
    { message: "Input must be between 1 and 100,000 characters" }
  )
}).strict();
var NotificationCategorySchema = z.enum(["info", "queue", "alert", "error", "system"]);
var GetNotificationsQuerySchema = z.object({
  limit: z.coerce.number().int().min(1).max(100).default(50),
  offset: z.coerce.number().int().min(0).default(0)
});
var MarkAsReadParamsSchema = z.object({
  id: UuidSchema
});
z.object({
  userId: UuidSchema,
  organizationId: UuidSchema,
  category: NotificationCategorySchema,
  title: z.string().trim().min(1).max(200),
  message: z.string().trim().min(1).max(1e3),
  actionUrl: z.string().url().optional()
}).strict();
z.object({
  ids: z.array(UuidSchema).min(1).max(500)
}).strict();

// src/hooks/sessions/sessionWebSocketUtils.ts
var liveTempMessageCounter = 0;
function createLiveTempMessageIdentity() {
  liveTempMessageCounter += 1;
  return {
    id: `temp-${liveTempMessageCounter}`,
    messageIndex: liveTempMessageCounter,
    createdAt: /* @__PURE__ */ new Date()
  };
}
function formatMessageEvent(event) {
  switch (event.type) {
    case "user_message":
      return event.text;
    case "assistant_message":
      return event.text;
    case "agent:started":
      return "Agent started reasoning";
    case "agent:reasoning":
      return `Reasoning (Iteration ${event.iteration})`;
    case "agent:tool_call":
      return `Tool: ${event.toolName}`;
    case "agent:tool_result":
      return event.success ? "Tool Result" : "Tool Result (Failed)";
    case "agent:completed":
      return "Agent completed";
    case "agent:error":
      return `Agent error: ${event.error}`;
  }
}
function getWebSocketBaseUrl(apiUrl) {
  const url = new URL(apiUrl);
  const protocol = url.protocol === "https:" ? "wss:" : "ws:";
  return `${protocol}//${url.host}`;
}

export { CreateSessionSchema, ExecutionIdParamsSchema, GetNotificationsQuerySchema, MarkAsReadParamsSchema, SessionIdParamSchema, WebSocketSessionTurnSchema, createLiveTempMessageIdentity, formatMessageEvent, getWebSocketBaseUrl, mergeSessionMessages };
