#!/bin/bash
h=$1; fail=0; ok(){ echo "  ok   $1"; }; no(){ echo "  FAIL $1"; fail=1; }
U=$(curl -s -m 15 https://$h/sitemap.xml | grep -oE '<loc>[^<]+</loc>' | sed 's/<[^>]*>//g' | grep "/digest/" | grep -v "/digest/$" | sed -n '2p')
echo "== $h  ($U)"
MD=$(curl -s -m 20 "$U.md"); CT=$(curl -s -o /dev/null -w '%{content_type}' -m 20 "$U.md")
[[ "$CT" == *text/markdown* ]] && ok ".md suffix -> $CT" || no ".md suffix -> $CT"
[[ "$MD" == "# "* ]] && ok ".md body starts with a heading" || no ".md body: '${MD:0:40}'"
grep -q '^Markdown-Version:' <<<"$MD" && ok "Markdown-Version line present" || no "no Markdown-Version line"
NEG=$(curl -s -m 20 -H 'Accept: text/markdown' "$U"); CTN=$(curl -s -o /dev/null -w '%{content_type}' -m 20 -H 'Accept: text/markdown' "$U")
[[ "$CTN" == *text/markdown* ]] && ok "Accept: text/markdown -> $CTN" || no "Accept negotiation -> $CTN"
[ "$NEG" = "$MD" ] && [ ${#MD} -gt 800 ] && ok "negotiated and .md byte-identical (${#MD} B)" || no "bodies differ (${#NEG}/${#MD})"
H=$(curl -sD /tmp/hh -m 20 -H 'Accept: text/html' "$U")
grep -qi '^link:.*\.md>; rel="alternate"; type="text/markdown"' /tmp/hh && ok "Link header on HTML" || no "Link header missing: $(grep -i '^link' /tmp/hh | head -1)"
grep -qi '^vary:.*accept' /tmp/hh && ok "Vary: Accept" || no "Vary missing"
grep -q 'rel="alternate" type="text/markdown"' <<<"$H" && ok "<link alternate markdown> in head" || no "no <link alternate markdown>"
grep -q 'class="nt-tip"' <<<"$H" && no "inline tooltip text still in article" || ok "no inline tooltip text in article body"
grep -q 'nt-term\[aria-label\]::after' <<<"$H" && ok "tooltip drawn by CSS from aria-label" || no "tooltip CSS rule missing"
TXT=$(curl -s -o /dev/null -w '%{http_code} %{content_type}' -m 20 "$U.txt"); [[ "$TXT" == 200*text/plain* ]] && ok ".txt still served as text/plain" || no ".txt regressed: $TXT"
curl -s -m 20 https://$h/changes.json | python3 -c 'import json,sys; d=json.load(sys.stdin); assert d["count"]>10 and d["changes"][0]["markdown"].endswith(".md"); print("  ok   changes.json (%d entries, newest %s)"%(d["count"],d["changes"][0]["published"][:10]))' || no "changes.json"
curl -s -m 20 https://$h/.well-known/txtfirst.json | python3 -c 'import json,sys; d=json.load(sys.stdin); assert d["txtfirst"]=="0.1"; print("  ok   .well-known/txtfirst.json")' || no "well-known"
curl -s -m 20 https://$h/llms.txt | grep -q "Accept: text/markdown" && ok "llms.txt explains negotiation" || no "llms.txt not updated"
printf "  weight: html %s B / md %s B = %.1fx\n" "${#H}" "${#MD}" "$(echo "scale=2;${#H}/${#MD}"|bc)"
[ $fail = 0 ] && echo "  PASS" || echo "  REVISE"
