import catalogAiTools from "./ai-tools.js";
import { createLogger } from "@open-mercato/shared/lib/logger";
const logger = createLogger("catalog");
const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
const SELECTION_CAP = 10;
function isUuid(value) {
  return typeof value === "string" && UUID_REGEX.test(value);
}
function parseSelectionIds(raw) {
  if (!raw) return [];
  const unique = /* @__PURE__ */ new Set();
  for (const token of raw.split(",")) {
    const trimmed = token.trim();
    if (isUuid(trimmed)) unique.add(trimmed);
    if (unique.size >= SELECTION_CAP) break;
  }
  return Array.from(unique);
}
function findTool(name) {
  return catalogAiTools.find((tool) => tool.name === name) ?? null;
}
function buildToolContext(container, tenantId, organizationId) {
  return {
    tenantId,
    organizationId,
    userId: null,
    container,
    userFeatures: [],
    isSuperAdmin: true,
    apiKeySecret: void 0,
    sessionId: void 0
  };
}
function renderContextBlock(label, payload) {
  return `## Page context \u2014 ${label}
${JSON.stringify(payload, null, 2)}`;
}
const SINGLE_PRODUCT_ENTITY_TYPES = /* @__PURE__ */ new Set([
  "product",
  "catalog.product",
  "catalog:catalog_product"
]);
const PRODUCTS_LIST_ENTITY_TYPES = /* @__PURE__ */ new Set([
  "catalog.products.list",
  "catalog.products.selection",
  "products.list",
  "products.selection"
]);
async function invokeTool(toolName, args, toolContext, reasonPrefix) {
  const tool = findTool(toolName);
  if (!tool) {
    logger.warn("resolvePageContext tool not registered", { reasonPrefix, toolName });
    return null;
  }
  try {
    const result = await tool.handler(args, toolContext);
    return result ?? null;
  } catch (error) {
    logger.warn("resolvePageContext tool failed; skipping", { reasonPrefix, toolName, reason: "hydration_error", err: error });
    return null;
  }
}
async function hydrateCatalogAssistantContext(input) {
  const tenantId = input.tenantId;
  if (!tenantId) return null;
  const entityType = input.entityType.trim().toLowerCase();
  if (!entityType) return null;
  const toolContext = buildToolContext(input.container, tenantId, input.organizationId);
  if (SINGLE_PRODUCT_ENTITY_TYPES.has(entityType)) {
    if (!isUuid(input.recordId)) return null;
    const result = await invokeTool(
      "catalog.get_product",
      { productId: input.recordId },
      toolContext,
      "catalog.catalog_assistant"
    );
    if (!result || typeof result !== "object") return null;
    if (result.found === false) return null;
    return renderContextBlock(`Product ${input.recordId}`, result);
  }
  if (PRODUCTS_LIST_ENTITY_TYPES.has(entityType)) {
    const ids = parseSelectionIds(input.recordId);
    if (ids.length === 0) return null;
    const result = await invokeTool(
      "catalog.list_selected_products",
      { productIds: ids },
      toolContext,
      "catalog.catalog_assistant"
    );
    if (!result || typeof result !== "object") return null;
    const { items, missingIds } = result;
    const summaries = Array.isArray(items) ? items.map((item) => item && typeof item === "object" ? item.product ?? null : null).filter((value) => value !== null) : [];
    if (summaries.length === 0) return null;
    return renderContextBlock(
      `Products selection (${summaries.length} of ${ids.length})`,
      { items: summaries, missingIds: missingIds ?? [] }
    );
  }
  return null;
}
async function hydrateMerchandisingAssistantContext(input) {
  const tenantId = input.tenantId;
  if (!tenantId) return null;
  const entityType = input.entityType.trim().toLowerCase();
  if (!entityType) return null;
  const toolContext = buildToolContext(input.container, tenantId, input.organizationId);
  if (SINGLE_PRODUCT_ENTITY_TYPES.has(entityType)) {
    if (!isUuid(input.recordId)) return null;
    const result = await invokeTool(
      "catalog.get_product_bundle",
      { productId: input.recordId },
      toolContext,
      "catalog.merchandising_assistant"
    );
    if (!result || typeof result !== "object") return null;
    if (result.found === false) return null;
    return renderContextBlock(`Product bundle ${input.recordId}`, result);
  }
  if (PRODUCTS_LIST_ENTITY_TYPES.has(entityType)) {
    const ids = parseSelectionIds(input.recordId);
    if (ids.length === 0) return null;
    const result = await invokeTool(
      "catalog.list_selected_products",
      { productIds: ids },
      toolContext,
      "catalog.merchandising_assistant"
    );
    if (!result || typeof result !== "object") return null;
    const { items, missingIds } = result;
    const bundles = Array.isArray(items) ? items : [];
    if (bundles.length === 0) return null;
    return renderContextBlock(
      `Products selection bundles (${bundles.length} of ${ids.length})`,
      {
        items: bundles,
        missingIds: missingIds ?? []
      }
    );
  }
  return null;
}
export {
  hydrateCatalogAssistantContext,
  hydrateMerchandisingAssistantContext
};
//# sourceMappingURL=ai-agents-context.js.map
