import {
  logger
} from "./chunk-K44MW7JJ.js";

// src/server/llm/vision-fallback.ts
var DEFAULT_CONFIG = {
  enabled: false,
  url: "http://localhost:11434",
  model: "qwen3.5:0.8b",
  timeout: 12e4
};
var config = { ...DEFAULT_CONFIG };
var configLoaded = false;
var descriptionCache = /* @__PURE__ */ new Map();
function clearDescriptionCache() {
  descriptionCache.clear();
}
function setVisionFallbackConfig(newConfig) {
  config = { ...config, ...newConfig };
  configLoaded = true;
  logger.debug("Vision fallback config updated", { config });
}
function getVisionFallbackConfig() {
  return { ...config };
}
function isVisionFallbackEnabled() {
  return config.enabled;
}
async function ensureVisionFallbackConfigLoaded() {
  if (configLoaded) return;
  try {
    const { loadGlobalConfig, getVisionFallback } = await import("./config-YU7NYZYG.js");
    const { getRuntimeConfig } = await import("./runtime-config-NPSPMRDA.js");
    const runtimeConfig = getRuntimeConfig();
    const mode = runtimeConfig.mode ?? "production";
    const globalConfig = await loadGlobalConfig(mode);
    const fallback = getVisionFallback(globalConfig);
    config = {
      enabled: fallback.enabled ?? false,
      url: fallback.url ?? "http://localhost:11434",
      model: fallback.model ?? "qwen3.5:0.8b",
      timeout: (fallback.timeout ?? 120) * 1e3
    };
    configLoaded = true;
    logger.debug("Vision fallback config loaded from global config", { config });
  } catch (error) {
    logger.warn("Failed to load vision fallback config from global config", {
      error: error instanceof Error ? error.message : String(error)
    });
  }
}
var IMAGE_PROMPT = `Describe this image in detail. Focus on:
- What the image shows (UI, diagram, photo, etc.)
- Any text visible in the image
- Layout and visual structure
- Key elements and their relationships

Provide a concise but comprehensive description.`;
async function describeImage(base64Data, options) {
  await ensureVisionFallbackConfigLoaded();
  if (!config.enabled) {
    return "[Image - vision fallback not enabled]";
  }
  const cacheKey = `${base64Data.slice(0, 100)}:${options?.context ?? ""}`;
  const cached = descriptionCache.get(cacheKey);
  if (cached) {
    logger.debug("Using cached image description");
    return cached;
  }
  const timeout = options?.timeout ?? config.timeout;
  try {
    const url = `${config.url}/api/chat`;
    const requestBody = {
      model: config.model,
      messages: [
        {
          role: "user",
          content: options?.context ? `${IMAGE_PROMPT}

Context: ${options.context}` : IMAGE_PROMPT,
          images: [base64Data]
        }
      ],
      stream: false,
      think: false
    };
    const timeoutController = new AbortController();
    const timeoutId = setTimeout(() => timeoutController.abort(), timeout);
    const signal = options?.signal ? AbortSignal.any([timeoutController.signal, options.signal]) : timeoutController.signal;
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json"
      },
      body: JSON.stringify(requestBody),
      signal
    });
    clearTimeout(timeoutId);
    if (!response.ok) {
      const errorText = await response.text().catch(() => "Unknown error");
      logger.error("Vision fallback API error", { status: response.status, error: errorText });
      return `[Image description failed: HTTP ${response.status}]`;
    }
    const data = await response.json();
    const description = data.message?.content?.trim();
    if (!description) {
      logger.warn("Vision fallback returned empty description");
      return "[Image - could not describe]";
    }
    descriptionCache.set(cacheKey, description);
    logger.debug("Cached image description", { cacheKey: cacheKey.slice(0, 20) });
    return description;
  } catch (error) {
    const message = error instanceof Error ? error.message : "Unknown error";
    logger.error("Vision fallback error", { error: message });
    if (message.includes("abort")) {
      return "[Image description timed out]";
    }
    return `[Image description failed: ${message}]`;
  }
}
async function describeImageFromDataUrl(dataUrl, options) {
  const base64Match = dataUrl.match(/^data:image\/[^;]+;base64,(.+)$/);
  if (!base64Match || !base64Match[1]) {
    return "[Invalid image data URL]";
  }
  return describeImage(base64Match[1], options);
}

export {
  descriptionCache,
  clearDescriptionCache,
  setVisionFallbackConfig,
  getVisionFallbackConfig,
  isVisionFallbackEnabled,
  ensureVisionFallbackConfigLoaded,
  describeImage,
  describeImageFromDataUrl
};
//# sourceMappingURL=chunk-SZKEGZIB.js.map