#!/usr/bin/env nu
# Fix markdown files with corrupted newlines
# Converts literal "\n" escape sequences back to actual newlines

def main [] {
    let docs_dir = "provisioning/docs/src"

    if not ($docs_dir | path exists) {
        print $"Error: ($docs_dir) directory not found"
        exit 1
    }

    print $"Scanning ($docs_dir) for corrupted markdown files..."

    # Find all markdown files
    let files = (
        glob ($docs_dir + "/**/*.md")
        | sort
    )

    print $"Found ($files | length) markdown files\n"

    mut fixed_count = 0
    mut checked_count = 0

    for file in $files {
        $checked_count += 1

        let content = (open $file)

        # Check if file contains literal \n (corrupted)
        # The file will have actual backslash followed by 'n' instead of newlines
        if ($content | str contains '\\n') {
            let fixed_content = (
                $content
                | str replace -a '\\n' "\n"
            )

            # Write back the fixed content
            $fixed_content | save -f $file
            $fixed_count += 1

            # Show progress
            let line_count = ($fixed_content | lines | length)
            print $"✓ Fixed: ($file) - ($line_count) lines"
        }
    }

    print $"\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
    print $"Summary:"
    print $"  Checked:  ($checked_count) files"
    print $"  Fixed:    ($fixed_count) files"
    print $"━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
}

main
