export const name = 'diagram';
export const description = 'Generate visual diagrams from descriptions (flowcharts, sequence diagrams, mind maps, ER diagrams)';

export async function execute(ctx) {
  const topic = ctx.args?.topic || ctx.args?.task || 'a simple flowchart';
  const timestamp = Date.now();

  const prompt = `You are an expert at creating Mermaid.js diagrams.

Generate a self-contained HTML file that displays a Mermaid diagram based on this request:
"${topic}"

Requirements:
- Single self-contained HTML file
- Include Mermaid.js via: <script src="https://cdn.jsdelivr.net/npm/mermaid/dist/mermaid.min.js"></script>
- Support any of: flowchart, sequence diagram, mind map, ER diagram, gantt, class diagram — choose the most appropriate type
- Initialize mermaid with: mermaid.initialize({ startOnLoad: true, theme: 'default' })
- Wrap diagram in <div class="mermaid">...</div>
- Clean, minimal styling: white background, centered content, readable font
- Include a title heading above the diagram
- Make the diagram detailed and accurate to the request

Respond with ONLY the HTML. Start with <!DOCTYPE html>.`;

  let html = await ctx.askLLM(prompt, { model: ctx.pickModel('build') });

  // Strip markdown code fences if present
  html = html.replace(/^```(?:html)?\s*\n?/i, '').replace(/\n?\s*```\s*$/, '').trim();

  if (html && !html.startsWith('<!')) {
    const htmlMatch = html.match(/(<!DOCTYPE html[\s\S]*<\/html>)/i);
    if (htmlMatch) html = htmlMatch[1];
  }

  if (!html) return 'Skipped: empty diagram output.';

  const filename = `diagram-${timestamp}.html`;
  const written = await ctx.writeOutputFile(filename, html);
  ctx.addEvent('skill', 'agent', `Created diagram: ${written.name}`, { path: written.publicPath });

  return { success: true, file: written.name };
}

export default { name, description, execute };
