#!/bin/bash

# Extract mermaid charts from markdown file

INPUT_FILE="define/시장조사-차트.md"
OUTPUT_DIR="define/charts"

echo "Extracting Mermaid charts from: $INPUT_FILE"
echo "Output directory: $OUTPUT_DIR"
echo ""

# Create output directory
mkdir -p "$OUTPUT_DIR"

# Counter
chart_num=0

# Read file and extract charts
in_mermaid=false
current_chart=""
current_title=""

while IFS= read -r line || [ -n "$line" ]; do
    # Check for section header (## number. title)
    if [[ $line =~ ^##[[:space:]]([0-9]+)\.[[:space:]](.+)$ ]]; then
        num="${BASH_REMATCH[1]}"
        title="${BASH_REMATCH[2]}"
        current_title=$(printf "chart%02d_%s" "$num" "${title// /_}")
        current_title="${current_title//\//_}"
    fi
    
    # Check for mermaid start
    if [[ $line == '```mermaid' ]]; then
        in_mermaid=true
        current_chart=""
        continue
    fi
    
    # Check for mermaid end
    if [[ $line == '```' ]] && $in_mermaid; then
        # Save chart
        if [ -n "$current_title" ]; then
            filename="${current_title}.mmd"
            echo "$current_chart" > "$OUTPUT_DIR/$filename"
            echo "  ✓ Saved: $filename"
            ((chart_num++))
        fi
        in_mermaid=false
        current_chart=""
        continue
    fi
    
    # Collect chart lines
    if $in_mermaid; then
        if [ -n "$current_chart" ]; then
            current_chart+=$'\n'
        fi
        current_chart+="$line"
    fi
done < "$INPUT_FILE"

echo ""
echo "✅ Successfully extracted $chart_num charts!"
echo ""
echo "Chart files saved in: $OUTPUT_DIR"
