const INLINE_ARTIFACT = /::codex-inline-artifact\{id="([a-z0-9-]+)" name="([^"]*)" url="(\/api\/sessions\/[^\s"/]+\/artifacts\/[a-z0-9-]+\/[^\s"]+)"\}/gi;
const ARTIFACT_PATH = /^\/api\/sessions\/[^/]+\/artifacts\/[a-z0-9-]+$/i;

export function assistantSegments(text) {
  const source = typeof text === "string" ? text : "";
  const segments = [];
  let cursor = 0;
  for (const match of source.matchAll(INLINE_ARTIFACT)) {
    if (match.index > cursor) segments.push({ kind: "markdown", text: source.slice(cursor, match.index) });
    segments.push({
      kind: "html",
      id: match[1],
      name: match[2].replaceAll('\\"', '"').replaceAll("\\\\", "\\"),
      url: match[3]
    });
    cursor = match.index + match[0].length;
  }
  if (cursor < source.length) segments.push({ kind: "markdown", text: source.slice(cursor) });
  return segments.length ? segments : [{ kind: "markdown", text: source }];
}

export function artifactInfo(href) {
  if (typeof href !== "string") return null;
  let url;
  try {
    url = new URL(href, "http://artifact.local");
  } catch {
    return null;
  }
  if (url.origin !== "http://artifact.local" || !ARTIFACT_PATH.test(url.pathname)) return null;
  const size = Number(url.searchParams.get("size"));
  const line = Number(url.searchParams.get("line"));
  return {
    url: href,
    name: safeLabel(url.searchParams.get("name")),
    mimeType: url.searchParams.get("mime") || "application/octet-stream",
    size: Number.isFinite(size) && size >= 0 ? size : undefined,
    line: Number.isInteger(line) && line > 0 ? line : undefined
  };
}

function safeLabel(value) {
  return String(value || "Artifact").replace(/[\u0000-\u001f]/g, "");
}
