#!/usr/bin/env python3
"""
Mermaid Chart Extractor
Extracts Mermaid charts from markdown and saves them as individual .mmd files
"""

import re
import os
from pathlib import Path


def extract_mermaid_charts(markdown_file, output_dir):
    """Extract all mermaid code blocks from markdown file"""

    # Read markdown file
    with open(markdown_file, 'r', encoding='utf-8') as f:
        content = f.read()

    # Find all mermaid code blocks
    pattern = r'```mermaid\n(.*?)```'
    matches = re.findall(pattern, content, re.DOTALL)

    # Create output directory
    os.makedirs(output_dir, exist_ok=True)

    # Extract chart titles from markdown headers
    title_pattern = r'## (\d+)\. (.+?)\n\n```mermaid'
    titles = re.findall(title_pattern, content, re.DOTALL)

    print(f"Found {len(matches)} Mermaid charts")

    # Save each chart as separate .mmd file
    for i, (chart_code, (num, title)) in enumerate(zip(matches, titles), 1):
        # Clean filename
        filename = f"chart{num:02d}_{title.replace(' ', '_').replace('/', '_')}.mmd"
        filepath = os.path.join(output_dir, filename)

        # Write mermaid code
        with open(filepath, 'w', encoding='utf-8') as f:
            f.write(chart_code.strip())

        print(f"  ✓ Saved: {filename}")

    return len(matches)


if __name__ == "__main__":
    # Configuration
    markdown_file = "define/시장조사-차트.md"
    output_dir = "define/charts"

    print(f"Extracting Mermaid charts from: {markdown_file}")
    print(f"Output directory: {output_dir}\n")

    count = extract_mermaid_charts(markdown_file, output_dir)

    print(f"\n✅ Successfully extracted {count} charts!")
    print(f"\nNext steps:")
    print(f"1. Use Mermaid Live Editor: https://mermaid.live/")
    print(f"2. Copy-paste each .mmd file content")
    print(f"3. Export as PNG or SVG")
