#!/usr/bin/env nu

# Fix markdown linting errors in documentation

def fix-code-fences [] {
  let files = glob "src/architecture/*.md"

  for $file in $files {
    print $"Processing $file"

    let content = open $file

    # Replace ``` with ```text for architecture diagrams
    let fixed = $content
      | str replace --all -r '```\n┌' '```text\n┌'
      | str replace --all -r '```\n{' '```nickel\n{'
      | str replace --all -r '```\n\[' '```yaml\n['
      | str replace --all -r '```\nuser:' '```yaml\nuser:'
      | str replace --all -r '```\nexport' '```nushell\nexport'
      | str replace --all -r '```\nlet' '```nushell\nlet'
      | str replace --all -r '```\npub' '```rust\npub'
      | str replace --all -r '```\n#' '```bash\n#'
      | str replace --all -r '```\nname:' '```yaml\nname:'
      | str replace --all -r '```\npermit' '```cedar\npermit'

    save -f $file $fixed
  }
}

def fix-table-spacing [] {
  let files = glob "src/architecture/*.md"

  for $file in $files {
    print $"Fixing tables in $file"

    let content = open $file

    # Fix table spacing - ensure | text | format
    let fixed = $content
      | str replace --all '|---|---|---|' '| --- | --- | --- |'
      | str replace --all '|------|------|------|' '| ------ | ------ | ------ |'
      | str replace --all '|----|---|' '| ---- | --- |'
      | str replace --all '|----|----|----|' '| ---- | ---- | ---- |'
      | str replace --all '|---|' '| --- |'

    save -f $file $fixed
  }
}

def fix-heading-punctuation [] {
  let files = glob "src/architecture/*.md"

  for $file in $files {
    print $"Fixing headings in $file"

    let content = open $file

    # Remove trailing colons from headings
    let fixed = $content
      | str replace --all -r '#### \*\*Other Services\*\*:' '#### Other Services'
      | str replace --all -r '## (.*):$' '## $1'
      | str replace --all -r '### (.*):$' '### $1'
      | str replace --all -r '#### (.*):$' '#### $1'

    save -f $file $fixed
  }
}

# Main execution
print "Fixing markdown errors..."
fix-code-fences
fix-table-spacing
fix-heading-punctuation
print "Done!"
