#!/bin/bash

# Full Quality & Security Check Script
# Run this manually before pushing to ensure code quality
# Usage: ./quality-check.sh [--fix]

set -e

CONFIG_DIR=".dev-config"
FIX_MODE=false
ERRORS=0

# Check if --fix flag is provided
if [ "$1" = "--fix" ]; then
    FIX_MODE=true
    echo "🔧 Running in FIX mode - will attempt to auto-fix issues"
    echo ""
fi

echo "╔════════════════════════════════════════════════════════════════╗"
echo "║      Full Quality & Security Check - No Compromises!          ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

# ============================================================================
# 1. JavaScript/TypeScript Linting
# ============================================================================
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔍 [1/6] JavaScript/TypeScript Linting (ESLint)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

cd plugins/translate-press-zone/backend-app/admin-panel

if [ "$FIX_MODE" = true ]; then
    if npm run lint -- --fix; then
        echo "✅ ESLint passed (auto-fixed)"
    else
        echo "❌ ESLint failed"
        ERRORS=$((ERRORS + 1))
    fi
else
    if npm run lint; then
        echo "✅ ESLint passed"
    else
        echo "❌ ESLint failed"
        ERRORS=$((ERRORS + 1))
    fi
fi

cd - > /dev/null
echo ""

# ============================================================================
# 2. TypeScript Type Checking
# ============================================================================
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔍 [2/6] TypeScript Type Checking"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

cd plugins/translate-press-zone/backend-app/admin-panel

if npm run type-check; then
    echo "✅ TypeScript type check passed"
else
    echo "❌ TypeScript type check failed"
    ERRORS=$((ERRORS + 1))
fi

cd - > /dev/null
echo ""

# ============================================================================
# 3. PHP Coding Standards (PHPCS)
# ============================================================================
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔍 [3/6] PHP Coding Standards (PHPCS)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if command -v phpcs >/dev/null 2>&1; then
    if [ -f "$CONFIG_DIR/phpcs.xml" ]; then
        if [ "$FIX_MODE" = true ] && command -v phpcbf >/dev/null 2>&1; then
            echo "Attempting to auto-fix with phpcbf..."
            phpcbf --standard="$CONFIG_DIR/phpcs.xml" plugins/translate-press-zone/ || true
        fi
        
        if phpcs --standard="$CONFIG_DIR/phpcs.xml" --runtime-set ignore_warnings_on_exit 1 plugins/translate-press-zone/; then
            echo "✅ PHPCS passed"
        else
            echo "❌ PHPCS failed"
            echo "💡 Run: phpcbf --standard=$CONFIG_DIR/phpcs.xml [file] to auto-fix"
            ERRORS=$((ERRORS + 1))
        fi
    else
        echo "⚠️  PHPCS config not found"
    fi
else
    echo "⚠️  PHPCS not installed"
    echo "💡 Install: composer global require squizlabs/php_codesniffer"
    ERRORS=$((ERRORS + 1))
fi
echo ""

# ============================================================================
# 4. PHP Static Analysis (Psalm)
# ============================================================================
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔍 [4/6] PHP Static Analysis (Psalm)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if command -v psalm >/dev/null 2>&1; then
    if [ -f "$CONFIG_DIR/psalm.xml" ]; then
        if psalm -c "$CONFIG_DIR/psalm.xml" --threads=max --no-cache; then
            echo "✅ Psalm passed"
        else
            echo "❌ Psalm found type errors"
            ERRORS=$((ERRORS + 1))
        fi
    else
        echo "⚠️  Psalm config not found"
    fi
else
    echo "⚠️  Psalm not installed"
    echo "💡 Install: composer global require vimeo/psalm"
    ERRORS=$((ERRORS + 1))
fi
echo ""

# ============================================================================
# 5. Security Vulnerability Scan (Trivy)
# ============================================================================
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔍 [5/6] Security Vulnerability Scan (Trivy)"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

if command -v trivy >/dev/null 2>&1; then
    if trivy fs --severity HIGH,CRITICAL --exit-code 1 .; then
        echo "✅ Trivy scan passed - No HIGH/CRITICAL vulnerabilities"
    else
        echo "❌ Trivy found security vulnerabilities"
        echo "💡 Review and update vulnerable dependencies"
        ERRORS=$((ERRORS + 1))
    fi
elif command -v podman >/dev/null 2>&1; then
    echo "Using Podman to run Trivy..."
    if podman run --rm -v "$(pwd):/src:Z" docker.io/aquasec/trivy fs --severity HIGH,CRITICAL --exit-code 1 /src; then
        echo "✅ Trivy scan passed"
    else
        echo "❌ Trivy found security vulnerabilities"
        ERRORS=$((ERRORS + 1))
    fi
elif command -v docker >/dev/null 2>&1; then
    echo "Using Docker to run Trivy..."
    if docker run --rm -v "$(pwd):/src" aquasec/trivy fs --severity HIGH,CRITICAL --exit-code 1 /src; then
        echo "✅ Trivy scan passed"
    else
        echo "❌ Trivy found security vulnerabilities"
        ERRORS=$((ERRORS + 1))
    fi
else
    echo "⚠️  Trivy not installed (and no Docker/Podman available)"
    echo "💡 Install: https://trivy.dev/latest/docs/installation/"
    echo "⚠️  Skipping security scan - THIS IS A SECURITY RISK!"
    ERRORS=$((ERRORS + 1))
fi
echo ""

# ============================================================================
# 6. Dependency Security Audit
# ============================================================================
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"
echo "🔍 [6/6] Dependency Security Audit"
echo "━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"

# NPM Audit
echo "Checking NPM dependencies..."
cd plugins/translate-press-zone/backend-app/admin-panel
if npm audit --audit-level=moderate; then
    echo "✅ NPM audit passed"
else
    echo "⚠️  NPM audit found vulnerabilities"
    echo "💡 Run: npm audit fix"
    ERRORS=$((ERRORS + 1))
fi
cd - > /dev/null

# Composer Audit (if composer.json exists)
if [ -f "plugins/translate-press-zone/composer.json" ]; then
    echo "Checking Composer dependencies..."
    cd plugins/translate-press-zone
    if command -v composer >/dev/null 2>&1; then
        if composer audit; then
            echo "✅ Composer audit passed"
        else
            echo "⚠️  Composer audit found vulnerabilities"
            echo "💡 Run: composer update"
            ERRORS=$((ERRORS + 1))
        fi
    else
        echo "⚠️  Composer not installed"
    fi
    cd - > /dev/null
fi
echo ""

# ============================================================================
# Summary
# ============================================================================
echo "╔════════════════════════════════════════════════════════════════╗"
echo "║                       CHECK SUMMARY                            ║"
echo "╚════════════════════════════════════════════════════════════════╝"
echo ""

if [ $ERRORS -eq 0 ]; then
    echo "✅ ✅ ✅  ALL CHECKS PASSED - Code quality verified!  ✅ ✅ ✅"
    echo ""
    echo "🚀 Safe to commit and push!"
    echo ""
    exit 0
else
    echo "❌ ❌ ❌  CHECKS FAILED ($ERRORS issue(s) found)  ❌ ❌ ❌"
    echo ""
    echo "🛑 DO NOT COMMIT until issues are fixed!"
    echo ""
    echo "📝 Quick Fix Guide:"
    echo "   1. JavaScript/TypeScript: npm run lint -- --fix"
    echo "   2. PHP Standards:         phpcbf --standard=.dev-config/phpcs.xml [file]"
    echo "   3. PHP Types:             Review Psalm output and fix type issues"
    echo "   4. Security:              Update vulnerable dependencies"
    echo "   5. Re-run:                ./quality-check.sh"
    echo ""
    echo "💡 Or run with auto-fix: ./quality-check.sh --fix"
    echo ""
    exit 1
fi
