/** The API can return legacy HTML, serialized editor.document, or a block array. */
export type RichTextContent = string | unknown[];

type BlockNoteBlock = {
  type: string;
  content?: unknown;
  props?: Record<string, unknown>;
  children?: BlockNoteBlock[];
};

type ParsedRichText =
  | { format: 'html'; html: string }
  | { format: 'blocknote'; blocks: BlockNoteBlock[] }
  | { format: 'invalid' };

const isRecord = (value: unknown): value is Record<string, unknown> =>
  typeof value === 'object' && value !== null && !Array.isArray(value);

const isBlock = (value: unknown, depth = 0): value is BlockNoteBlock =>
  depth < 64 &&
  isRecord(value) &&
  typeof value.type === 'string' &&
  value.type.length > 0 &&
  (value.props === undefined || isRecord(value.props)) &&
  (value.children === undefined ||
    (Array.isArray(value.children) && value.children.every((child) => isBlock(child, depth + 1))));

export function parseRichText(value: unknown): ParsedRichText {
  if (value == null) return { format: 'html', html: '' };

  let parsed: unknown = value;
  if (typeof value === 'string') {
    const text = value.trim();
    // Ordinary HTML/text never needs the BlockNote runtime.
    if (!text.startsWith('[')) return { format: 'html', html: text };
    try {
      parsed = JSON.parse(text);
    } catch {
      // Do not print a damaged BlockNote document as raw JSON/HTML.
      return /"type"\s*:/.test(text) ? { format: 'invalid' } : { format: 'html', html: text };
    }
    // Preserve legacy text such as "[1956]".
    if (Array.isArray(parsed) && parsed.length && parsed.every((item) => !isRecord(item))) {
      return { format: 'html', html: text };
    }
  }

  return Array.isArray(parsed) && parsed.every((block) => isBlock(block))
    ? { format: 'blocknote', blocks: parsed }
    : { format: 'invalid' };
}

function hasText(value: unknown, depth = 0): boolean {
  if (depth >= 64) return false;
  if (typeof value === 'string') return Boolean(value.trim());
  if (Array.isArray(value)) return value.some((item) => hasText(item, depth + 1));
  if (!isRecord(value)) return false;
  // Inline text, links and table rows/cells; IDs and formatting are not content.
  return ['text', 'content', 'rows', 'cells'].some((key) => hasText(value[key], depth + 1));
}

export function hasRichTextContent(value: unknown): boolean {
  const parsed = parseRichText(value);
  if (parsed.format === 'html') return Boolean(parsed.html);
  if (parsed.format === 'invalid') return false;

  const hasBlockContent = (block: BlockNoteBlock): boolean =>
    block.type === 'divider' ||
    hasText(block.content) ||
    (typeof block.props?.url === 'string' && Boolean(block.props.url.trim())) ||
    Boolean(block.children?.some(hasBlockContent));

  return parsed.blocks.some(hasBlockContent);
}
