import { P as PaginatedConversationsResponseSchema, C as ConversationSchema, a as PaginatedTracesResponseSchema } from './source-selection-hOQHZ-fn.js';

class MockGenerator {
  poolSize = 120;
  // ----- CONVERSATIONS -----
  async fetchConversations(limit, phoneFilter, lastConversationId) {
    await delay(150);
    return this.generateConversations(limit, phoneFilter, lastConversationId);
  }
  generateConversations(limit, phoneFilter, lastConversationId) {
    const now = Date.now();
    const items = [];
    for (let i = 0; i < this.poolSize; i++) {
      const id = String(1e5 + i);
      items.push({
        conversationId: id,
        medium: i % 2 === 0 ? "phone" : "whatsapp",
        phoneNumber: `+44 7700 ${String(1e3 + i % 90).padStart(4, "0")}`,
        duration: Math.floor(Math.random() * 600),
        createdAt: now - i * 36e5
      });
    }
    let filtered = items;
    if (phoneFilter) {
      const q = phoneFilter.replace(/\s+/g, "");
      filtered = items.filter((it) => it.phoneNumber?.replace(/\s+/g, "").includes(q));
    }
    filtered.sort((a, b) => b.createdAt - a.createdAt);
    if (lastConversationId) {
      const idx = filtered.findIndex((it) => it.conversationId === lastConversationId);
      if (idx >= 0) filtered = filtered.slice(idx + 1);
    }
    const pageItems = filtered.slice(0, limit);
    const nextLastConversationId = pageItems.length ? pageItems[pageItems.length - 1].conversationId : void 0;
    return { limit, items: pageItems, lastConversationId: nextLastConversationId };
  }
  // ----- MIXED TRACES -----
  async fetchTraces(conversationId) {
    await delay(150);
    return { items: this.generateTraces(conversationId) };
  }
  generateTraces(conversationId) {
    const rng = mulberry32(hashString(conversationId));
    const count = Math.floor(rng() * 5) + 3;
    const now = Date.now();
    const traces = Array.from({ length: count }, (_, i) => {
      const ts = now - (count - i) * 3e4;
      const kind = i % 3;
      if (kind === 0) {
        return {
          traceType: "CONVERSATIONAL",
          traceId: `conv-${conversationId}-${i}`,
          conversationId,
          eventName: "received-message",
          role: "user",
          medium: "phone",
          content: `Hello (${i})`,
          createdAt: ts
        };
      }
      if (kind === 1) {
        return {
          traceType: "API_CALL",
          traceId: `api-${conversationId}-${i}`,
          conversationId,
          operationName: "getBooking",
          method: "GET",
          path: `/bookings/${conversationId}`,
          createdAt: ts,
          durationMs: Math.floor(rng() * 200) + 50,
          status: 200,
          ok: true
        };
      }
      return {
        traceType: "STEP",
        traceId: `step-${conversationId}-${i}`,
        conversationId,
        scopeId: `scope-${i}`,
        workflowId: `workflow-${i}`,
        workflowRunId: `run-${conversationId}-${i}`,
        name: `main`,
        renderedPrompt: `Rendered prompt for ${conversationId}/${i}`,
        receivedContext: { foo: "bar" },
        receivedPrompt: `User says #${i}`,
        createdAt: ts,
        stringifiedConversation: `user: hi
agent: ok (${i})`,
        response: `response ${i}`,
        model: "gpt-4"
      };
    });
    traces.sort((a, b) => a.createdAt - b.createdAt);
    return traces;
  }
}
function delay(ms) {
  return new Promise((r) => setTimeout(r, ms));
}
function hashString(s) {
  let h = 1779033703 ^ s.length;
  for (let i = 0; i < s.length; i++) {
    h = Math.imul(h ^ s.charCodeAt(i), 3432918353);
    h = h << 13 | h >>> 19;
  }
  return h >>> 0;
}
function mulberry32(seed) {
  return function() {
    let t = seed += 1831565813;
    t = Math.imul(t ^ t >>> 15, t | 1);
    t ^= t + Math.imul(t ^ t >>> 7, t | 61);
    return ((t ^ t >>> 14) >>> 0) / 4294967296;
  };
}
const mockGenerator = new MockGenerator();
const SOURCE_HEADER = "x-bosun-telescope-source";
class TelescopeClient {
  /**
   * @param fetchFn Custom fetch function (e.g., from SvelteKit's load context). Defaults to global fetch if not provided.
   */
  constructor(fetchFn = globalThis.fetch, sourceId) {
    this.fetchFn = fetchFn;
    this.sourceId = sourceId;
  }
  setSourceId(sourceId) {
    this.sourceId = sourceId;
  }
  /**
   * Get the actual URL to use (always uses proxy)
   */
  getUrl(path) {
    const cleanPath = path.startsWith("/") ? path.slice(1) : path;
    const pathWithoutDev = cleanPath.replace(/^dev\//, "");
    return `/traces/api/proxy/${pathWithoutDev}`;
  }
  async fetch(method = "GET", path, schema) {
    const url = this.getUrl(path);
    const headers = {};
    if (this.sourceId && this.sourceId.trim()) {
      headers[SOURCE_HEADER] = this.sourceId;
    }
    const response = await this.fetchFn(url, { method, headers });
    if (!response) {
      throw new Error("No response from server");
    }
    if (!response.ok) {
      throw new Error(`Error fetching data: ${response.statusText}`);
    }
    if (schema) {
      return schema.parse(await response.json());
    }
    return response;
  }
  /**
   * Get a list of conversations
   * @param phoneNumber full or partial phone number
   * @param limit number of conversations to fetch
   * @param lastConversationId id of the last conversation from the previous page, for pagination
   * @returns a list of conversations
   */
  async getConversations(params = {}) {
    const searchParams = new URLSearchParams({ limit: params.limit?.toString() ?? "10" });
    if (params.lastConversationId)
      searchParams.append("lastConversationId", params.lastConversationId);
    if (params.phoneNumber) searchParams.append("phoneNumber", params.phoneNumber);
    if (params.agentId) searchParams.append("agentId", params.agentId);
    const res = await this.fetch("GET", `/conversations?${searchParams.toString()}`);
    if (!res.ok) {
      throw new Error(`Error fetching conversations: ${res.status} ${res.statusText}`);
    }
    const json = await res.json();
    if (Array.isArray(json?.items)) {
      json.items = json.items.map((it) => ({
        ...it,
        phoneNumber: typeof it?.phoneNumber === "string" ? it.phoneNumber : ""
      }));
    } else {
      json.items = [];
    }
    return PaginatedConversationsResponseSchema.parse(json);
  }
  /**
   * Get a single conversation by ID
   * @param conversationId the conversation ID
   * @returns a single conversation
   */
  async getConversation(conversationId) {
    return await this.fetch(
      "GET",
      `/conversations/${conversationId}`,
      ConversationSchema
    );
  }
  /**
   * Get mixed traces for a conversation (chronological timeline)
   * @param conversationId the conversation ID
   * @param limit number of traces to fetch
   * @param lastTraceId id of the last trace from the previous page, for pagination
   * @returns paginated traces
   */
  async getTraces(conversationId, limit, lastTraceId) {
    const params = new URLSearchParams();
    if (limit) params.set("limit", String(limit));
    if (lastTraceId) params.set("lastTraceId", lastTraceId);
    const path = `/conversations/${conversationId}/traces${params.toString() ? `?${params.toString()}` : ""}`;
    const res = await this.fetch("GET", path);
    if (!res.ok) {
      throw new Error(`Failed to fetch traces: ${res.status} ${res.statusText}`);
    }
    return PaginatedTracesResponseSchema.parse(await res.json());
  }
  // Backwards-compatible aliases (older UI paths)
  getCalls(params = {}) {
    return this.getConversations(params);
  }
  getCall(conversationId) {
    return this.getConversation(conversationId);
  }
  getStepTraces(conversationId, limit) {
    return this.getTraces(conversationId, limit);
  }
}

export { TelescopeClient as T, mockGenerator as m };
//# sourceMappingURL=client-tqD_VlIn.js.map
