#!/usr/bin/env nu
# Fix MD060 table formatting errors
# This script adds spaces around pipes in markdown tables

def fix-table-line [line: string]: string -> string {
    # Skip if line doesn't contain table pipes
    if not ($line | str contains "|") {
        return $line
    }

    # Skip if line starts with code block
    if ($line | str starts-with "```") {
        return $line
    }

    # Check if this is a table line (starts with | or has | surrounded by content)
    let trimmed = $line | str trim
    if not ($trimmed | str starts-with "|") {
        return $line
    }

    # Process the line character by character
    let chars = $line | split chars
    let len = $chars | length

    mut result = []
    mut i = 0
    mut in_code_span = false

    while $i < $len {
        let char = $chars | get $i

        # Track code spans (backticks)
        if $char == "`" {
            $in_code_span = not $in_code_span
            $result = ($result | append $char)
            $i = $i + 1
            continue
        }

        # Don't process pipes inside code spans
        if $in_code_span {
            $result = ($result | append $char)
            $i = $i + 1
            continue
        }

        if $char == "|" {
            # Check if we need space before pipe
            if $i > 0 {
                let prev = $chars | get ($i - 1)
                if $prev != " " and $prev != "|" {
                    $result = ($result | append " ")
                }
            }

            $result = ($result | append $char)

            # Check if we need space after pipe
            if ($i + 1) < $len {
                let next = $chars | get ($i + 1)
                if $next != " " and $next != "|" and $next != "\n" {
                    $result = ($result | append " ")
                }
            }
        } else {
            $result = ($result | append $char)
        }

        $i = $i + 1
    }

    $result | str join
}

def process-file [file: path] {
    let content = open $file --raw
    let lines = $content | lines

    mut in_code_block = false
    mut new_lines = []

    for line in $lines {
        # Track code blocks
        if ($line | str trim | str starts-with "```") {
            $in_code_block = not $in_code_block
            $new_lines = ($new_lines | append $line)
            continue
        }

        # Don't process lines inside code blocks
        if $in_code_block {
            $new_lines = ($new_lines | append $line)
            continue
        }

        # Fix table lines
        let fixed = fix-table-line $line
        $new_lines = ($new_lines | append $fixed)
    }

    let new_content = $new_lines | str join "\n"

    # Preserve trailing newline if original had one
    if ($content | str ends-with "\n") {
        $new_content + "\n" | save -f $file
    } else {
        $new_content | save -f $file
    }
}

def main [
    --dry-run (-d)  # Show what would be changed without modifying files
] {
    # Get list of files with MD060 errors
    let files = (
        markdownlint-cli2 --config .markdownlint-cli2.jsonc "**/*.md"
        | complete
        | get stderr
        | lines
        | where { $in | str contains "MD060" }
        | each { $in | split row ":" | first }
        | uniq
    )

    if ($files | is-empty) {
        print "No MD060 errors found"
        return
    }

    print $"Found ($files | length) files with MD060 errors"

    for file in $files {
        if $dry_run {
            print $"Would fix: ($file)"
        } else {
            print $"Fixing: ($file)"
            process-file $file
        }
    }

    print "Done"
}
