import { marked } from 'marked';
import DOMPurify from 'dompurify';
import type { AgentRunState } from '@/types/workbench';

marked.setOptions({
  gfm: true,
  breaks: true,
});

/**
 * Renders markdown to HTML and sanitizes it before it's ever allowed near
 * `dangerouslySetInnerHTML`. Sources feeding this (agent-generated report
 * markdown, Hyper-Loop/Template service responses) are LLM output and remote
 * API responses -- neither is a trusted-safe-HTML source, so unsanitized
 * output here would be a stored-XSS hole in a desktop app whose webview has
 * Tauri IPC access (file read/write, PTY spawn, credential login).
 */
export function renderMarkdownHtml(markdown: string): string {
  const input = String(markdown || '').trim();
  if (!input) return '';
  const html = marked.parse(input) as string;
  return DOMPurify.sanitize(html);
}

export function summarizeMarkdown(markdown: string): { title: string; sections: string[] } {
  const lines = String(markdown || '').split('\n');
  let title = 'Analysis report';
  const sections: string[] = [];
  for (const line of lines) {
    const h1 = line.match(/^#\s+(.+)$/);
    if (h1 && title === 'Analysis report') {
      title = h1[1].replace(/[*_`]/g, '').trim();
      continue;
    }
    const h2 = line.match(/^##\s+(.+)$/);
    if (h2 && sections.length < 8) {
      sections.push(h2[1].replace(/[*_`]/g, '').trim());
    }
  }
  return { title, sections };
}

export function createInitialAgentRunState(): AgentRunState {
  return {
    status: 'idle',
    toolCount: 0,
    iterationCount: 0,
    reportMarkdown: '',
    summaryTitle: '',
    summarySections: [],
  };
}
