import { getBackendBaseURL } from "../config";
import type { AgentThread } from "../threads";

const ARTIFACTS_REPLACE_SENTINEL = "__deerflow_replace_artifacts__";

export function urlOfArtifact({
  filepath,
  threadId,
  download = false,
  isMock = false,
}: {
  filepath: string;
  threadId: string;
  download?: boolean;
  isMock?: boolean;
}) {
  if (isMock) {
    return `${getBackendBaseURL()}/mock/api/threads/${threadId}/artifacts${filepath}${download ? "?download=true" : ""}`;
  }
  return `${getBackendBaseURL()}/api/threads/${threadId}/artifacts${filepath}${download ? "?download=true" : ""}`;
}

export function extractArtifactsFromThread(thread: AgentThread) {
  return sanitizeArtifactPaths(thread.values.artifacts);
}

export function resolveArtifactURL(absolutePath: string, threadId: string) {
  return `${getBackendBaseURL()}/api/threads/${threadId}/artifacts${absolutePath}`;
}

export function sanitizeArtifactPaths(paths: string[] | undefined | null) {
  return (paths ?? []).filter((path) => path !== ARTIFACTS_REPLACE_SENTINEL);
}
