#!/bin/bash

# Sitemap Testing Script
# Validates sitemap.xml structure and content
# Usage: ./scripts/test-sitemap.sh

set -e

SITEMAP_URL="http://localhost:10000/sitemap.xml"
PROD_SITEMAP_URL="https://workroot.in/sitemap.xml"

echo "🧪 Testing Sitemap..."
echo ""

# Test 1: Sitemap accessible
echo "1️⃣  Testing sitemap accessibility..."
HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" "$SITEMAP_URL")
if [ "$HTTP_CODE" = "200" ]; then
  echo "   ✅ Sitemap is accessible (HTTP $HTTP_CODE)"
else
  echo "   ❌ Sitemap returned HTTP $HTTP_CODE"
  exit 1
fi

# Test 2: Valid XML
echo "2️⃣  Testing XML validity..."
if curl -s "$SITEMAP_URL" | xmllint --noout - 2>/dev/null; then
  echo "   ✅ Sitemap is valid XML"
else
  echo "   ⚠️  XML validation failed (xmllint not installed or XML invalid)"
fi

# Test 3: Count URLs
echo "3️⃣  Counting URLs..."
URL_COUNT=$(curl -s "$SITEMAP_URL" | grep -c '<loc>' || echo "0")
echo "   📊 Found $URL_COUNT URLs in sitemap"

# Test 4: Check for blog posts
echo "4️⃣  Checking for blog posts..."
BLOG_COUNT=$(curl -s "$SITEMAP_URL" | grep -c 'workroot.in/blog/[^<]*</loc>' || echo "0")
if [ "$BLOG_COUNT" -gt 0 ]; then
  echo "   ✅ Found $BLOG_COUNT blog posts"
else
  echo "   ⚠️  No blog posts found (might be normal if no published posts)"
fi

# Test 5: Verify domain
echo "5️⃣  Verifying domain..."
if curl -s "$SITEMAP_URL" | grep -q 'workroot.in'; then
  echo "   ✅ Correct domain (workroot.in)"
else
  echo "   ❌ Wrong domain found in sitemap"
fi

# Test 6: Check lastmod dates
echo "6️⃣  Checking lastmod dates..."
LASTMOD_COUNT=$(curl -s "$SITEMAP_URL" | grep -c '<lastmod>' || echo "0")
if [ "$LASTMOD_COUNT" -gt 0 ]; then
  echo "   ✅ Found $LASTMOD_COUNT lastmod dates"
else
  echo "   ⚠️  No lastmod dates found"
fi

# Test 7: Verify robots.txt reference
echo "7️⃣  Checking robots.txt..."
if curl -s "http://localhost:10000/robots.txt" | grep -q 'Sitemap:'; then
  echo "   ✅ Sitemap referenced in robots.txt"
else
  echo "   ❌ Sitemap not in robots.txt"
fi

echo ""
echo "📋 Summary:"
echo "   Total URLs: $URL_COUNT"
echo "   Blog posts: $BLOG_COUNT"
echo "   Lastmod dates: $LASTMOD_COUNT"
echo ""
echo "✨ Sitemap test complete!"
echo ""
echo "To view sitemap:"
echo "   Local: curl $SITEMAP_URL"
echo "   Prod: curl $PROD_SITEMAP_URL"
