#!/usr/bin/env bash
# Deterministic Gitea Markdown renderer stub for check.sh contract tests.
set -euo pipefail

if printf '%s\n' "${PR_BODY}" | grep -Fq '<!--'; then
  exit 0
fi

printf '%s\n' "${PR_BODY}" | awk '
  {
    line=$0
    lower=tolower(line)
    pos=1
    while (pos <= 4 && substr(line, pos, 1) == " ") pos++
    char=substr(line, pos, 1)
    run=0
    if (char == "`" || char == "~") while (substr(line, pos + run, 1) == char) run++
    rest=substr(line, pos + run)
    if (in_fence) {
      if (pos <= 4 && char == fence_char && run >= fence_run && rest ~ /^[[:blank:]]*$/) in_fence=0
      next
    }
    if (in_script) {
      if (lower ~ /<\/script[[:blank:]]*>/) in_script=0
      next
    }
    if (pos <= 4 && run >= 3 && (char == "~" || index(rest, "`") == 0)) {
      in_fence=1
      fence_char=char
      fence_run=run
      next
    }
    if (lower ~ /^[ ]{0,3}<script([[:blank:]>])/) {
      in_script=1
      next
    }
    if (lower ~ /^[ ]{0,3}<details([[:blank:]>])/) {
      print "<details>"
      next
    }
    if (line ~ /^## Tracking[[:space:]]*$/) print "<h2>Tracking</h2>"
    else if (line ~ /^## Attribution[[:space:]]*$/) print "<h2>Attribution</h2>"
    else if (line ~ /Authored-By:.*<noreply@[[:alnum:].-]+>/) {
      email=line
      sub(/^.*</, "", email)
      sub(/>.*/, "", email)
      sub(/ <noreply@[[:alnum:].-]+>.*/, "", line)
      print line " <a href=\"mailto:" email "\">" email "</a>"
    }
    else {
      gsub(/</, "\\&lt;", line)
      gsub(/>/, "\\&gt;", line)
      print line
    }
  }
'
