#!/bin/bash
# Comprehensive check for gaps, errors, issues, and warnings
# in the Order of St John seal deployment process

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}[CHECK]${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")/../.."

ISSUES=0
WARNINGS=0
ERRORS=0

echo ""
log_info "=== Comprehensive Seal Deployment Issue Check ==="
echo ""

# 1. Pre-deployment checks
log_info "1. PRE-DEPLOYMENT CHECKS"
echo ""

# Check script permissions
log_info "   Checking script permissions..."
for script in scripts/deploy/prepare-all-credential-seals.sh \
              scripts/validation/validate-seal-files.sh \
              scripts/deploy/complete-seal-deployment.sh \
              scripts/deploy/update-manifest-seal-urls.sh; do
    if [ -f "${script}" ]; then
        if [ -x "${script}" ]; then
            log_success "   ${script}: Executable"
        else
            log_error "   ${script}: Not executable"
            ((ERRORS++))
        fi
    else
        log_error "   ${script}: File not found"
        ((ERRORS++))
    fi
done

# Check script syntax
log_info "   Checking script syntax..."
for script in scripts/deploy/prepare-all-credential-seals.sh \
              scripts/validation/validate-seal-files.sh \
              scripts/deploy/complete-seal-deployment.sh \
              scripts/deploy/update-manifest-seal-urls.sh; do
    if bash -n "${script}" 2>/dev/null; then
        log_success "   ${script}: Syntax valid"
    else
        log_error "   ${script}: Syntax errors"
        ((ERRORS++))
    fi
done

# Check directories
log_info "   Checking directories..."
[ -d "assets/credential-images/svg" ] && log_success "   SVG directory exists" || { log_error "   SVG directory missing"; ((ERRORS++)); }
[ -d "assets/credential-images/png" ] && log_success "   PNG directory exists" || { log_warning "   PNG directory missing (will be created)"; ((WARNINGS++)); }

# Check SVG files
log_info "   Checking SVG files..."
EXPECTED_SVGS=(
    "digital-bank-seal.svg"
    "iccc-seal.svg"
    "iccc-provost-marshals-seal.svg"
    "diplomatic-security-seal.svg"
)

for svg in "${EXPECTED_SVGS[@]}"; do
    if [ -f "assets/credential-images/svg/${svg}" ]; then
        log_success "   ${svg}: Exists"
        # Validate SVG structure
        if grep -q "viewBox\|<svg" "assets/credential-images/svg/${svg}"; then
            log_success "     Valid SVG structure"
        else
            log_error "     Invalid SVG structure"
            ((ERRORS++))
        fi
        if grep -q "maltese-cross\|Maltese Cross" "assets/credential-images/svg/${svg}" -i; then
            log_success "     Contains Maltese Cross"
        else
            log_warning "     Maltese Cross reference not found"
            ((WARNINGS++))
        fi
    else
        log_error "   ${svg}: Missing"
        ((ERRORS++))
    fi
done

# Check conversion tools
log_info "   Checking conversion tools..."
HAS_CONVERTER=false
if command -v convert &> /dev/null; then
    log_success "   ImageMagick: Available"
    HAS_CONVERTER=true
elif command -v inkscape &> /dev/null; then
    log_success "   Inkscape: Available"
    HAS_CONVERTER=true
elif command -v node &> /dev/null && node -e "require('sharp')" 2>/dev/null; then
    log_success "   Node.js with sharp: Available"
    HAS_CONVERTER=true
else
    log_warning "   No conversion tool available (ImageMagick, Inkscape, or sharp)"
    log_warning "   PNG conversion will fail without one of these"
    ((WARNINGS++))
fi

echo ""

# 2. During deployment checks
log_info "2. DURING DEPLOYMENT CHECKS"
echo ""

# Run deployment and capture output
log_info "   Running deployment script..."
DEPLOY_LOG="/tmp/seal-deployment-check.log"
if ./scripts/deploy/complete-seal-deployment.sh > "${DEPLOY_LOG}" 2>&1; then
    log_success "   Deployment script completed"
else
    log_error "   Deployment script failed"
    ((ERRORS++))
fi

# Check for errors in log
log_info "   Analyzing deployment log..."
ERROR_COUNT=$(grep -i "error\|failed\|✗" "${DEPLOY_LOG}" 2>/dev/null | grep -v "WARNING\|warning" | wc -l || echo "0")
WARNING_COUNT=$(grep -i "warning\|!" "${DEPLOY_LOG}" 2>/dev/null | wc -l || echo "0")

if [ "${ERROR_COUNT}" -gt 0 ]; then
    log_error "   Found ${ERROR_COUNT} error(s) in deployment log"
    ((ERRORS+=ERROR_COUNT))
    echo "   Sample errors:"
    grep -i "error\|failed\|✗" "${DEPLOY_LOG}" 2>/dev/null | grep -v "WARNING\|warning" | head -5 | sed 's/^/     /'
fi

if [ "${WARNING_COUNT}" -gt 0 ]; then
    log_warning "   Found ${WARNING_COUNT} warning(s) in deployment log"
    ((WARNINGS+=WARNING_COUNT))
fi

echo ""

# 3. Post-deployment checks
log_info "3. POST-DEPLOYMENT CHECKS"
echo ""

# Check PNG files
log_info "   Checking generated PNG files..."
PNG_COUNT=$(find assets/credential-images/png -name "*.png" -type f 2>/dev/null | wc -l)
if [ "${PNG_COUNT}" -gt 0 ]; then
    log_success "   ${PNG_COUNT} PNG file(s) generated"
    
    # Validate PNG files
    INVALID_PNG=0
    for png in assets/credential-images/png/*.png; do
        if [ -f "${png}" ]; then
            if file "${png}" | grep -q "PNG"; then
                size_kb=$(du -k "${png}" | cut -f1)
                if [ "${size_kb}" -gt 500 ]; then
                    log_warning "   $(basename "${png}"): Large size (${size_kb}KB, recommend <100KB)"
                    ((WARNINGS++))
                fi
            else
                log_error "   $(basename "${png}"): Invalid PNG"
                ((INVALID_PNG++))
                ((ERRORS++))
            fi
        fi
    done
    
    if [ ${INVALID_PNG} -eq 0 ]; then
        log_success "   All PNG files are valid"
    fi
else
    if [ "${HAS_CONVERTER}" = "false" ]; then
        log_warning "   No PNG files generated (conversion tool not available)"
    else
        log_error "   No PNG files generated (conversion may have failed)"
        ((ERRORS++))
    fi
fi

# Check generated reports
log_info "   Checking generated reports..."
REPORTS=(
    "assets/credential-images/png/MANIFEST.txt"
    "assets/credential-images/png/VALIDATION_REPORT.txt"
    "assets/credential-images/DEPLOYMENT_CHECKLIST.md"
    "assets/credential-images/DEPLOYMENT_SUMMARY.md"
)

for report in "${REPORTS[@]}"; do
    if [ -f "${report}" ]; then
        log_success "   $(basename "${report}"): Generated"
    else
        log_warning "   $(basename "${report}"): Not generated"
        ((WARNINGS++))
    fi
done

# Check manifest templates
log_info "   Checking manifest templates..."
for manifest in manifests/entra/*-manifest-template.json; do
    if [ -f "${manifest}" ]; then
        filename=$(basename "${manifest}")
        if jq -e '.display.logo.uri' "${manifest}" >/dev/null 2>&1; then
            log_success "   ${filename}: Valid JSON"
            if grep -q "cdn.theorder.org/images.*seal" "${manifest}"; then
                log_success "     Has seal URL reference"
            else
                log_warning "     Missing seal URL reference"
                ((WARNINGS++))
            fi
        else
            log_error "   ${filename}: Invalid JSON"
            ((ERRORS++))
        fi
    fi
done

echo ""

# 4. Summary
log_info "=== ISSUE SUMMARY ==="
echo ""
log_success "Checks passed: Multiple"
if [ ${WARNINGS} -gt 0 ]; then
    log_warning "Warnings: ${WARNINGS}"
fi
if [ ${ERRORS} -gt 0 ]; then
    log_error "Errors: ${ERRORS}"
fi

echo ""
if [ ${ERRORS} -eq 0 ] && [ ${WARNINGS} -eq 0 ]; then
    log_success "No issues found! Deployment is ready."
    exit 0
elif [ ${ERRORS} -eq 0 ]; then
    log_warning "Deployment has warnings but no critical errors."
    exit 0
else
    log_error "Deployment has errors that need to be fixed."
    exit 1
fi

