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

connect_timeout=0
total_timeout=0
while [ "$#" -gt 0 ]; do
  case "$1" in
    --connect-timeout)
      [ "${2:-}" = "5" ] || exit 2
      connect_timeout=1
      shift 2
      ;;
    --max-time)
      [ "${2:-}" = "15" ] || exit 2
      total_timeout=1
      shift 2
      ;;
    *) shift ;;
  esac
done
[ "${connect_timeout}" -eq 1 ] && [ "${total_timeout}" -eq 1 ] || exit 2

if printf '%s\n' "${PR_BODY}" | grep -Fq '[[stall-renderer]]'; then
  exit 28
fi

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 (lower ~ /^[ ]{0,3}<details([[:blank:]>])/) {
      attributes=lower
      gsub(/"[^"]*"/, "", attributes)
      if (attributes ~ /[[:blank:]]open([[:blank:]=>]|$)/) sub(/<details open>/, "<details open=\"\">", line)
      print line
      next
    }
    if (line ~ /^## Tracking[[:space:]]*$/) print "<h2>Tracking</h2>"
    else if (line ~ /^## Attribution[[:space:]]*$/) print "<h2>Attribution</h2>"
    else if (line ~ /^- Fixes[[:space:]]/) print "<li>" substr(line, 3) "</li>"
    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
    }
  }
'
