import type { CardItem, JsonValue } from "../types";
import type { RuntimeItem } from "./runtimeTypes";

export function cloneJsonValue<T extends JsonValue>(value: T | null | undefined): T | undefined {
  if (value === null || value === undefined) return undefined;
  try {
    return JSON.parse(JSON.stringify(value)) as T;
  } catch {
    return value ?? undefined;
  }
}

export function normalizeTemplateState(
  value: Record<string, JsonValue> | undefined,
): Record<string, JsonValue> {
  const cloned = cloneJsonValue((value || {}) as JsonValue);
  return cloned && typeof cloned === "object" && !Array.isArray(cloned)
    ? (cloned as Record<string, JsonValue>)
    : {};
}

export function runtimeItemId(item: RuntimeItem): string {
  if (isCardItem(item)) {
    return `card:${item.serverId || item.id}`;
  }
  return `workbench:${item.chatId}:${item.id}`;
}

function isCardItem(item: RuntimeItem): item is CardItem {
  return "lane" in item;
}

export function looksLikeHtml(content: string): boolean {
  return /^\s*<[a-zA-Z]/.test(content);
}
