#!/usr/bin/env bash
# orca-verify-render.sh — bash-side render-contract validator (grill C-16).
# Reads a render-bundle JSON file (one Artifact per line, or a JSON array)
# and validates each entry against the orca.emit/v1 schema.
# Exit 0 if all valid; non-zero with a structured error per failure to stderr.
# Source: scripts/lib/orca-log.sh for structured error logging (C-17).
#
# Usage: orca-verify-render.sh <bundle.json>

set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=lib/orca-log.sh
. "$SCRIPT_DIR/lib/orca-log.sh"

EXPECTED_SCHEMA="orca.emit/v1"

if [ "$#" -lt 1 ]; then
	orca_log_error "verify-render" "-" "failed" "missing bundle argument"
	echo "usage: $0 <bundle.json>" >&2
	exit 2
fi

bundle="$1"
if [ ! -f "$bundle" ]; then
	orca_log_error "verify-render" "$bundle" "failed" "bundle file not found"
	echo "error: bundle not found: $bundle" >&2
	exit 2
fi

errors=0
total=0

# Read the bundle line-by-line. Each line should be a JSON object.
# (The Go emitter writes one Artifact per line for line-delimited parsing.)
while IFS= read -r line; do
	# Skip blank lines and comments.
	[ -z "$line" ] && continue
	case "$line" in \#*) continue ;; esac
	total=$((total + 1))
	# Validate schema_version field presence and value (crude JSON grep; no jq dep).
	# Check schema_version via a simple substring test.
	schema_match=0
	if printf '%s' "$line" | grep -q "\"schema_version\":\"$EXPECTED_SCHEMA\""; then
		schema_match=1
	fi
	if [ "$schema_match" -eq 1 ]; then
		# schema_version matches. Check kind, path, mode presence.
		for field in kind path mode; do
			if ! printf '%s' "$line" | grep -q "\"$field\":"; then
				orca_log_error "verify-render" "$bundle" "failed" "missing field: $field"
				echo "error: line $total missing field: $field" >&2
				errors=$((errors + 1))
				continue 2
			fi
		done
	elif printf '%s' "$line" | grep -q '"schema_version":'; then
		orca_log_error "verify-render" "$bundle" "failed" "schema_version mismatch on line $total"
		echo "error: line $total schema_version mismatch (expected $EXPECTED_SCHEMA)" >&2
		errors=$((errors + 1))
	else
		orca_log_error "verify-render" "$bundle" "failed" "missing schema_version on line $total"
		echo "error: line $total missing schema_version" >&2
		errors=$((errors + 1))
	fi
done < "$bundle"

if [ "$errors" -gt 0 ]; then
	orca_log_error "verify-render" "$bundle" "failed" "$errors of $total artifacts invalid"
	echo "verify-render: $errors of $total artifacts invalid" >&2
	exit 1
fi

orca_log_info "verify-render" "$bundle" "ok" ""
echo "verify-render: $total artifacts valid"
exit 0