import type { WikiPage } from "../types/wiki-model";

export function normalizeMermaidSource(chart: string): string {
  return chart
    .replace(/^```mermaid\s*/i, "")
    .replace(/^mermaid\s*/i, "")
    .replace(/\s*```$/i, "")
    .replace(/\r\n?/g, "\n")
    .trim();
}

/**
 * Normalize mermaid source without server-side validation.
 *
 * Mermaid + DOMPurify require a browser DOM that is not available in
 * Node.js.  The client-side MermaidDiagram component already renders
 * diagrams with a graceful fallback for invalid syntax, so server-side
 * validation is unnecessary.
 */
export async function validateMermaidSource(chart: string): Promise<{
  valid: boolean;
  normalized: string;
  error?: string;
}> {
  const normalized = normalizeMermaidSource(chart);
  if (!normalized) {
    return { valid: false, normalized, error: "Empty Mermaid diagram" };
  }
  return { valid: true, normalized };
}

export async function downgradeInvalidMermaidBlocksInMarkdown(markdown: string): Promise<{
  markdown: string;
  diagramErrors: string[];
}> {
  // No server-side validation — return markdown unchanged.
  return { markdown, diagramErrors: [] };
}

export async function validateWikiPageMermaid(page: WikiPage): Promise<WikiPage> {
  // Normalize diagram sources but never reject them.
  const sections = await Promise.all(
    page.sections.map(async (section) => {
      if (section.type === "diagram" && section.diagram) {
        const normalized = normalizeMermaidSource(section.diagram.mermaid);
        return {
          ...section,
          diagram: { ...section.diagram, mermaid: normalized },
        };
      }
      return section;
    }),
  );

  return { ...page, sections };
}
