# Mermaid Chart Extractor
# Extracts Mermaid charts from markdown and saves them as individual .mmd files

$markdownFile = "define/시장조사-차트.md"
$outputDir = "define/charts"

Write-Host "Extracting Mermaid charts from: $markdownFile"
Write-Host "Output directory: $outputDir`n"

# Create output directory
if (-not (Test-Path $outputDir)) {
    New-Item -ItemType Directory -Path $outputDir | Out-Null
}

# Read markdown file
$content = Get-Content $markdownFile -Raw -Encoding UTF8

# Extract all mermaid blocks with their section headers
$pattern = '## (\d+)\. (.+?)\n\n```mermaid\n(.*?)```'
$matches = [regex]::Matches($content, $pattern, [System.Text.RegularExpressions.RegexOptions]::Singleline)

Write-Host "Found $($matches.Count) Mermaid charts`n"

# Save each chart
$count = 0
foreach ($match in $matches) {
    $num = $match.Groups[1].Value
    $title = $match.Groups[2].Value
    $chartCode = $match.Groups[3].Value

    # Clean filename
    $filename = "chart$($num.PadLeft(2,'0'))_$($title.Replace(' ', '_').Replace('/', '_')).mmd"
    $filepath = Join-Path $outputDir $filename

    # Write mermaid code
    $chartCode.Trim() | Out-File -FilePath $filepath -Encoding UTF8 -NoNewline

    Write-Host "  ✓ Saved: $filename"
    $count++
}

Write-Host "`n✅ Successfully extracted $count charts!"
Write-Host "`nChart files saved in: $outputDir"
Write-Host "`nNext steps:"
Write-Host "1. Use Mermaid Live Editor: https://mermaid.live/"
Write-Host "2. Copy-paste each .mmd file content"
Write-Host "3. Export as PNG or SVG"
