#!/bin/bash
# Schema-slot tests for render.sh
# Renders fixture site.yaml files and verifies JSON-LD output.
#
# Run from repo root: ./tests/schema-test.sh
set -euo pipefail

SCRIPT_DIR=$(cd "$(dirname "$0")" && pwd)
ROOT_DIR=$(cd "$SCRIPT_DIR/.." && pwd)
FIXTURES="$SCRIPT_DIR/fixtures"

pass=0
fail=0

assert_jsonld() {
    local name="$1" yaml="$2" template="$3" expected_type="$4"
    local out
    out=$("$ROOT_DIR/render.sh" "$yaml" "$ROOT_DIR/templates/${template}.html")

    local script
    script=$(echo "$out" | grep -oE '<script type="application/ld\+json">[^<]+</script>' || true)
    if [ -z "$script" ]; then
        echo "  [FAIL] $name — no JSON-LD <script> found"
        fail=$((fail + 1))
        return
    fi

    local json
    json=$(echo "$script" | sed -E 's|<script[^>]*>||; s|</script>||')

    if ! echo "$json" | jq empty 2>/dev/null; then
        echo "  [FAIL] $name — invalid JSON: $json"
        fail=$((fail + 1))
        return
    fi

    local ctx atype
    ctx=$(echo "$json" | jq -r '."@context"')
    atype=$(echo "$json" | jq -r '."@type"')

    if [ "$ctx" != "https://schema.org" ]; then
        echo "  [FAIL] $name — wrong @context: $ctx"
        fail=$((fail + 1))
        return
    fi
    if [ "$atype" != "$expected_type" ]; then
        echo "  [FAIL] $name — expected @type=$expected_type, got $atype"
        fail=$((fail + 1))
        return
    fi
    if echo "$json" | jq -e 'has("type")' >/dev/null; then
        echo "  [FAIL] $name — raw 'type' key still present (should be '@type')"
        fail=$((fail + 1))
        return
    fi

    echo "  [PASS] $name — @type=$atype, valid JSON-LD"
    pass=$((pass + 1))
}

assert_no_jsonld() {
    local name="$1" yaml="$2" template="$3"
    local out
    out=$("$ROOT_DIR/render.sh" "$yaml" "$ROOT_DIR/templates/${template}.html")
    if echo "$out" | grep -q 'application/ld+json'; then
        echo "  [FAIL] $name — unexpected JSON-LD present"
        fail=$((fail + 1))
        return
    fi
    echo "  [PASS] $name — no JSON-LD (as expected)"
    pass=$((pass + 1))
}

echo "== schema-test.sh =="

# Explicit type
assert_jsonld "person-explicit (type: Person)" \
    "$FIXTURES/person-explicit.yaml" "person-dark" "Person"

# Default from template (no .schema.type)
assert_jsonld "product-default (default Product)" \
    "$FIXTURES/product-default.yaml" "product-dark" "Product"

assert_jsonld "article-editorial (default Article)" \
    "$FIXTURES/article-editorial.yaml" "editorial" "Article"

# No schema → no script
assert_no_jsonld "no-schema (empty slot)" \
    "$FIXTURES/no-schema.yaml" "minimal"

echo "== $pass passed, $fail failed =="
[ $fail -eq 0 ]
