#!/bin/bash
# Validate Order of St John seal files
# Checks SVG structure, PNG quality, and file integrity

set -euo pipefail

GREEN='\033[0;32m'
BLUE='\033[0;34m'
YELLOW='\033[1;33m'
RED='\033[0;31m'
NC='\033[0m'

log_info() { echo -e "${BLUE}[VALIDATE]${NC} $1"; }
log_success() { echo -e "${GREEN}[✓]${NC} $1"; }
log_warning() { echo -e "${YELLOW}[!]${NC} $1"; }
log_error() { echo -e "${RED}[✗]${NC} $1"; }

cd "$(dirname "$0")/../.."

SVG_DIR="assets/credential-images/svg"
PNG_DIR="assets/credential-images/png"

CHECKS_PASSED=0
CHECKS_FAILED=0
CHECKS_WARNING=0

check() {
    local name=$1
    local command=$2
    
    if eval "${command}" > /dev/null 2>&1; then
        log_success "${name}"
        ((CHECKS_PASSED++))
        return 0
    else
        log_error "${name}"
        ((CHECKS_FAILED++))
        return 1
    fi
}

check_warning() {
    local name=$1
    local command=$2
    
    if eval "${command}" > /dev/null 2>&1; then
        log_success "${name}"
        ((CHECKS_PASSED++))
        return 0
    else
        log_warning "${name}"
        ((CHECKS_WARNING++))
        return 1
    fi
}

echo ""
log_info "=== Order of St John Seal Validation ==="
echo ""

# Check directories exist
log_info "1. Directory Structure"
check "SVG directory exists" "[ -d '${SVG_DIR}' ]"
check "PNG directory exists" "[ -d '${PNG_DIR}' ]"

# Check for required SVG files
log_info "2. Required SVG Files"
EXPECTED_SEALS=(
    "digital-bank-seal.svg"
    "iccc-seal.svg"
    "iccc-provost-marshals-seal.svg"
    "diplomatic-security-seal.svg"
)

for seal in "${EXPECTED_SEALS[@]}"; do
    check "Required seal exists: ${seal}" "[ -f '${SVG_DIR}/${seal}' ]"
done

# Validate SVG structure
log_info "3. SVG File Structure"
for svg_file in "${SVG_DIR}"/*.svg; do
    if [ -f "${svg_file}" ]; then
        filename=$(basename "${svg_file}")
        
        # Check for Maltese Cross
        if grep -q "maltese-cross\|Maltese Cross\|maltese" "${svg_file}" -i; then
            log_success "${filename}: Contains Maltese Cross reference"
            ((CHECKS_PASSED++))
        else
            log_warning "${filename}: Maltese Cross reference not found"
            ((CHECKS_WARNING++))
        fi
        
        # Check for OSJ reference
        if grep -q "OSJ\|ORDER OF ST JOHN\|ORDO S. IOANNIS" "${svg_file}"; then
            log_success "${filename}: Contains OSJ reference"
            ((CHECKS_PASSED++))
        else
            log_warning "${filename}: OSJ reference not found"
            ((CHECKS_WARNING++))
        fi
        
        # Check SVG is valid XML
        if xmllint --noout "${svg_file}" 2>/dev/null; then
            log_success "${filename}: Valid SVG/XML"
            ((CHECKS_PASSED++))
        else
            check_warning "${filename}: XML validation (xmllint not available)" "true"
        fi
        
        # Check viewBox exists
        if grep -q 'viewBox="0 0' "${svg_file}"; then
            log_success "${filename}: Has viewBox"
            ((CHECKS_PASSED++))
        else
            log_warning "${filename}: Missing viewBox"
            ((CHECKS_WARNING++))
        fi
    fi
done

# Validate PNG files
log_info "4. PNG File Validation"
PNG_COUNT=0
for png_file in "${PNG_DIR}"/*.png; do
    if [ -f "${png_file}" ]; then
        ((PNG_COUNT++))
        filename=$(basename "${png_file}")
        
        # Check if valid PNG
        if file "${png_file}" | grep -q "PNG"; then
            log_success "${filename}: Valid PNG"
            ((CHECKS_PASSED++))
            
            # Check file size (should be under 100KB for credentials)
            size_kb=$(du -k "${png_file}" | cut -f1)
            if [ "${size_kb}" -lt 100 ]; then
                log_success "${filename}: Size OK (${size_kb}KB)"
                ((CHECKS_PASSED++))
            else
                log_warning "${filename}: Large size (${size_kb}KB, recommend <100KB)"
                ((CHECKS_WARNING++))
            fi
        else
            log_error "${filename}: Invalid PNG"
            ((CHECKS_FAILED++))
        fi
    fi
done

if [ ${PNG_COUNT} -eq 0 ]; then
    log_warning "No PNG files found (run prepare-all-credential-seals.sh first)"
    ((CHECKS_WARNING++))
fi

# Check manifest templates reference seals
log_info "5. Manifest Template References"
MANIFEST_DIR="manifests/entra"
if [ -d "${MANIFEST_DIR}" ]; then
    for manifest in "${MANIFEST_DIR}"/*-manifest-template.json; do
        if [ -f "${manifest}" ]; then
            filename=$(basename "${manifest}")
            if grep -q "cdn.theorder.org/images.*seal" "${manifest}"; then
                log_success "${filename}: References seal image"
                ((CHECKS_PASSED++))
            else
                log_warning "${filename}: Seal image reference not found"
                ((CHECKS_WARNING++))
            fi
        fi
    done
fi

# Summary
echo ""
log_info "=== Validation Summary ==="
log_success "Passed: ${CHECKS_PASSED}"
if [ ${CHECKS_FAILED} -gt 0 ]; then
    log_error "Failed: ${CHECKS_FAILED}"
fi
if [ ${CHECKS_WARNING} -gt 0 ]; then
    log_warning "Warnings: ${CHECKS_WARNING}"
fi

TOTAL=$((CHECKS_PASSED + CHECKS_FAILED + CHECKS_WARNING))
if [ ${TOTAL} -gt 0 ]; then
    PERCENTAGE=$((CHECKS_PASSED * 100 / TOTAL))
    echo ""
    if [ ${CHECKS_FAILED} -eq 0 ]; then
        log_success "All critical checks passed! (${PERCENTAGE}%)"
        exit 0
    else
        log_error "Some checks failed (${PERCENTAGE}%)"
        exit 1
    fi
fi

