#!/usr/bin/env bash
set -Eeuo pipefail

BASE_URL="${1:-https://marlothparkcentral.com}"
EXPECTED_VERSION="${2:-6.82.190}"
BASE_URL="${BASE_URL%/}"
TMP_DIR="$(mktemp -d)"
trap 'rm -rf "$TMP_DIR"' EXIT

pass() { printf 'PASS  %s\n' "$1"; }
fail() { printf 'FAIL  %s\n' "$1" >&2; exit 1; }

request() {
  local path="$1" prefix="$2"
  curl --silent --show-error --connect-timeout 12 --max-time 45 \
    --dump-header "$TMP_DIR/${prefix}.headers" --output "$TMP_DIR/${prefix}.body" \
    "$BASE_URL$path"
  awk 'toupper($1) ~ /^HTTP\// {code=$2} END {print code}' "$TMP_DIR/${prefix}.headers"
}

header_value() {
  local file="$1" name="$2"
  awk -v name="$name" 'BEGIN{IGNORECASE=1} $0 ~ "^" name ":" {sub(/^[^:]+:[[:space:]]*/, ""); sub(/\r$/, ""); value=$0} END{print value}' "$file"
}

expect_status() {
  local path="$1" expected="$2" key="$3" code
  code="$(request "$path" "$key")"
  [[ "$code" == "$expected" ]] || fail "$path returned $code; expected $expected"
  pass "$path → $expected"
}

expect_redirect() {
  local path="$1" target="$2" key="$3" code location normalized
  code="$(request "$path" "$key")"
  [[ "$code" == "301" ]] || fail "$path returned $code; expected 301"
  location="$(header_value "$TMP_DIR/${key}.headers" Location)"
  normalized="${location#${BASE_URL}}"
  [[ "$normalized" == "$target" || "$normalized" == "$target/" ]] || fail "$path Location=$location; expected $target"
  pass "$path → 301 $target"
}

expect_status "/api/build-info" 200 build_info
grep -Eq '"buildVersion"[[:space:]]*:[[:space:]]*"'"$EXPECTED_VERSION"'"' "$TMP_DIR/build_info.body" || fail "/api/build-info does not report version $EXPECTED_VERSION"
pass "/api/build-info reports $EXPECTED_VERSION"

expect_status "/sitemap.xml" 200 sitemap
content_type="$(header_value "$TMP_DIR/sitemap.headers" Content-Type)"
[[ "$content_type" =~ (application|text)/xml ]] || fail "/sitemap.xml Content-Type is '$content_type'"
[[ -z "$(header_value "$TMP_DIR/sitemap.headers" Location)" ]] || fail "/sitemap.xml unexpectedly redirects"
grep -q '<urlset' "$TMP_DIR/sitemap.body" || fail "/sitemap.xml body is not an XML urlset"
! grep -Eqi 'prelaunch-slot|top-featured-position-|featured-position-|basic-position-|/accommodation/marlothi-safari-home' "$TMP_DIR/sitemap.body" || fail "/sitemap.xml includes noindex/placeholder/alternate accommodation URLs"
pass "/sitemap.xml is direct XML and excludes accommodation placeholders"

expect_status "/robots.txt" 200 robots
grep -Fq "Sitemap: https://marlothparkcentral.com/sitemap.xml" "$TMP_DIR/robots.body" || fail "/robots.txt has no canonical sitemap declaration"
! grep -Eq '^Disallow:[[:space:]]*/guides/?$' "$TMP_DIR/robots.body" || fail "/robots.txt blocks /guides"
pass "/robots.txt is canonical and does not block public guides"

primary_routes=(
  / /stay /accommodation /local /local-options /services /restaurants
  /safari-drives /guides /free-guides /route-atlas /contact
)
i=0
for route in "${primary_routes[@]}"; do
  expect_status "$route" 200 "primary_$((i++))"
done

retired_paths=(
  /lib/ /data/ /components/ /2026/05/01/hello-world/ /sample-page/
)
i=0
for route in "${retired_paths[@]}"; do
  expect_status "$route" 410 "gone_$((i++))"
done

expect_redirect "/accommodation/marlothi-safari-home" "/stay" redirect_stay
expect_redirect "/local/caroline-frozen-meals" "/restaurants/caroline-frozen-meals" redirect_restaurant
expect_redirect "/local/nkosi-mobile-spa" "/local-options/nkosi-mobile-spa" redirect_option
expect_redirect "/local/kruger-pride-safaris" "/safari-drives/kruger-pride-safaris" redirect_safari
expect_redirect "/local-options/busy-bee-shuttle" "/local/busy-bee-shuttle" redirect_service
expect_redirect "/local/food-dining" "/restaurants" redirect_category

python3 - "$BASE_URL" "$TMP_DIR/sitemap.body" <<'PY'
import sys, urllib.request, urllib.error, xml.etree.ElementTree as ET
from urllib.parse import urlsplit
base, sitemap_path = sys.argv[1], sys.argv[2]
root = ET.parse(sitemap_path).getroot()
namespace = {'s': 'http://www.sitemaps.org/schemas/sitemap/0.9'}
urls = [node.text for node in root.findall('.//s:loc', namespace) if node.text]
errors=[]
for canonical_url in urls:
    parsed = urlsplit(canonical_url)
    if parsed.scheme != 'https' or parsed.netloc != 'marlothparkcentral.com':
        errors.append(f'{canonical_url}: sitemap URL is not canonical HTTPS')
        continue
    request_url = base.rstrip('/') + (parsed.path or '/')
    if parsed.query:
        request_url += '?' + parsed.query
    req=urllib.request.Request(request_url, method='GET', headers={'User-Agent':'MPC-Launch-Contract/1.0'})
    opener=urllib.request.build_opener(urllib.request.HTTPHandler())
    try:
        response=opener.open(req, timeout=45)
        code=response.getcode()
        final=response.geturl()
        response.read(1024)
    except urllib.error.HTTPError as exc:
        code=exc.code; final=exc.geturl()
    except Exception as exc:
        errors.append(f'{canonical_url}: {type(exc).__name__}: {exc}')
        continue
    if code != 200 or urlsplit(final).path.rstrip('/') != parsed.path.rstrip('/'):
        errors.append(f'{canonical_url}: status={code} final={final}')
if errors:
    print('Sitemap route contract failures:', file=sys.stderr)
    print('\n'.join(errors), file=sys.stderr)
    raise SystemExit(1)
print(f'PASS  all {len(urls)} canonical sitemap URLs return direct 200 responses')
PY

printf '\nMPC launch response contract passed for %s\n' "$BASE_URL"
