#!/usr/bin/env bash
set -Eeuo pipefail
HOST='edu.learnitive.com'
resolve=(--resolve "$HOST:443:127.0.0.1")
fail(){ printf '[Learnitive edu local verify] ERROR: %s\n' "$*" >&2; exit 1; }
request(){ curl --noproxy '*' --silent --show-error --max-time 12 "$@"; }
status(){ curl --noproxy '*' --silent --show-error --max-time 12 --output /dev/null --write-out '%{http_code}' "$@"; }
headers(){ curl --noproxy '*' --silent --show-error --max-time 12 --head "$@"; }

code="$(status "${resolve[@]}" "https://$HOST/features")"
[[ "$code" == 200 ]] || fail "/features returned $code"
body="$(request "${resolve[@]}" "https://$HOST/features")"
grep -Eqi '<title>[^<]*Features[^<]*Learnitive</title>' <<<"$body" || fail '/features title is not route-specific.'
grep -Fq "https://$HOST/features" <<<"$body" || fail '/features canonical is not edu staging.'
grep -Eqi 'name="robots"[^>]*content="[^"]*noindex|content="[^"]*noindex[^"]*"[^>]*name="robots"' <<<"$body" || fail '/features initial HTML is not noindex.'

feature_headers="$(headers "${resolve[@]}" "https://$HOST/features")"
grep -Eqi '^x-robots-tag: .*noindex' <<<"$feature_headers" || fail 'staging vhost is missing X-Robots-Tag noindex.'
grep -Eqi '^content-security-policy: .*wss://edu\.learnitive\.com' <<<"$feature_headers" || fail 'staging CSP does not allow the edu WebSocket origin.'

manifest_code="$(status "${resolve[@]}" "https://$HOST/manifest.json")"
[[ "$manifest_code" == 200 ]] || fail "/manifest.json returned $manifest_code"
manifest_headers="$(headers "${resolve[@]}" "https://$HOST/manifest.json")"
grep -Eqi '^content-type: application/(manifest\+json|json)' <<<"$manifest_headers" || fail '/manifest.json has the wrong content type.'
manifest_body="$(request "${resolve[@]}" "https://$HOST/manifest.json")"
grep -Fq '"name": "Learnitive"' <<<"$manifest_body" || fail '/manifest.json is not the Learnitive PWA manifest.'

robots="$(request "${resolve[@]}" "https://$HOST/robots.txt")"
grep -Fxq 'Disallow: /' <<<"$robots" || fail 'robots.txt does not disallow all staging crawling.'
if grep -Fq 'Sitemap:' <<<"$robots"; then fail 'staging robots.txt must not advertise sitemap.xml.'; fi

compare="$(request "${resolve[@]}" "https://$HOST/compare/overleaf")"
grep -Fq 'data-interactive-prerender=' <<<"$compare" || fail '/compare/overleaf lacks substantive initial HTML.'

hidden_code="$(status "${resolve[@]}" "https://$HOST/compare/replit")"
[[ "$hidden_code" == 404 ]] || fail "/compare/replit returned $hidden_code instead of 404"

health_code="$(status "${resolve[@]}" "https://$HOST/api/health")"
[[ "$health_code" == 200 ]] || fail "/api/health returned $health_code"

printf '[Learnitive edu local verify] PASS: edu vhost, staging noindex, production-shaped SSR, PWA manifest, curated comparison surface and health endpoint verified on 127.0.0.1.\n'
