#!/bin/bash

# Desk-Moloni v3.0 Production Readiness Validator
# Author: Descomplicar.pt
# Version: 3.0.0
# License: Commercial

set -e

# Color codes for output
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
PURPLE='\033[0;35m'
CYAN='\033[0;36m'
NC='\033[0m' # No Color

# Configuration
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
MODULE_DIR="$(dirname "$SCRIPT_DIR")"
REPORT_FILE="/tmp/desk-moloni-production-readiness-$(date +%Y%m%d-%H%M%S).txt"
CRITICAL_FAILURES=0
HIGH_FAILURES=0
MEDIUM_FAILURES=0
LOW_FAILURES=0

# Functions
log() {
    echo -e "${GREEN}[VALIDATE]${NC} $1" | tee -a "$REPORT_FILE"
}

critical() {
    echo -e "${RED}[CRITICAL]${NC} $1" | tee -a "$REPORT_FILE"
    ((CRITICAL_FAILURES++))
}

high() {
    echo -e "${RED}[HIGH]${NC} $1" | tee -a "$REPORT_FILE"
    ((HIGH_FAILURES++))
}

medium() {
    echo -e "${YELLOW}[MEDIUM]${NC} $1" | tee -a "$REPORT_FILE"
    ((MEDIUM_FAILURES++))
}

low() {
    echo -e "${BLUE}[LOW]${NC} $1" | tee -a "$REPORT_FILE"
    ((LOW_FAILURES++))
}

pass() {
    echo -e "${GREEN}[PASS]${NC} $1" | tee -a "$REPORT_FILE"
}

# Production readiness banner
echo "========================================================================"
echo "              DESK-MOLONI v3.0 PRODUCTION READINESS VALIDATOR"
echo "========================================================================"
echo "Validation Report: $REPORT_FILE"
echo "Validation Date: $(date)"
echo ""

log "Starting comprehensive production readiness validation..."

# 1. Module Structure Validation
echo ""
log "=== MODULE STRUCTURE VALIDATION ==="

# Check core files exist
CORE_FILES=(
    "desk_moloni.php"
    "composer.json"
    "phpunit.xml"
    "VERSION"
    "README.md"
)

for file in "${CORE_FILES[@]}"; do
    if [[ -f "$MODULE_DIR/$file" ]]; then
        pass "Core file exists: $file"
    else
        critical "Missing core file: $file"
    fi
done

# Check directory structure
CORE_DIRECTORIES=(
    "assets"
    "cli"
    "config"
    "controllers"
    "database"
    "docs"
    "helpers"
    "language"
    "libraries"
    "models"
    "scripts"
    "src"
    "tests"
    "views"
)

for dir in "${CORE_DIRECTORIES[@]}"; do
    if [[ -d "$MODULE_DIR/$dir" ]]; then
        pass "Core directory exists: $dir"
    else
        high "Missing core directory: $dir"
    fi
done

# Check specific implementation files
IMPLEMENTATION_FILES=(
    "libraries/Encryption.php"
    "database/migrations/001_create_desk_moloni_tables.sql"
    "config/config.php"
    "cli/queue_processor.php"
    "scripts/install.sh"
    "scripts/security_audit.sh"
    "scripts/performance_report.sh"
)

for file in "${IMPLEMENTATION_FILES[@]}"; do
    if [[ -f "$MODULE_DIR/$file" ]]; then
        pass "Implementation file exists: $file"
    else
        high "Missing implementation file: $file"
    fi
done

# 2. Test Infrastructure Validation
echo ""
log "=== TEST INFRASTRUCTURE VALIDATION ==="

# Count test files
TEST_FILE_COUNT=$(find "$MODULE_DIR/tests" -name "*Test.php" 2>/dev/null | wc -l)
if [[ $TEST_FILE_COUNT -ge 20 ]]; then
    pass "Test suite comprehensive: $TEST_FILE_COUNT test files"
elif [[ $TEST_FILE_COUNT -ge 10 ]]; then
    medium "Test suite adequate: $TEST_FILE_COUNT test files"
else
    high "Test suite insufficient: $TEST_FILE_COUNT test files (minimum 20 required)"
fi

# Check test categories
TEST_CATEGORIES=(
    "tests/contract"
    "tests/integration"
    "tests/security"
    "tests/performance"
    "tests/unit"
    "tests/database"
)

for category in "${TEST_CATEGORIES[@]}"; do
    if [[ -d "$MODULE_DIR/$category" ]]; then
        TEST_COUNT=$(find "$MODULE_DIR/$category" -name "*Test.php" | wc -l)
        if [[ $TEST_COUNT -gt 0 ]]; then
            pass "Test category implemented: $category ($TEST_COUNT tests)"
        else
            medium "Test category empty: $category"
        fi
    else
        high "Missing test category: $category"
    fi
done

# Validate PHPUnit configuration
if [[ -f "$MODULE_DIR/phpunit.xml" ]]; then
    if grep -q "testsuites" "$MODULE_DIR/phpunit.xml"; then
        pass "PHPUnit configuration includes test suites"
    else
        medium "PHPUnit configuration missing test suites"
    fi
    
    if grep -q "coverage" "$MODULE_DIR/phpunit.xml"; then
        pass "PHPUnit configuration includes coverage reporting"
    else
        low "PHPUnit configuration missing coverage reporting"
    fi
else
    critical "PHPUnit configuration file missing"
fi

# 3. Security Implementation Validation
echo ""
log "=== SECURITY IMPLEMENTATION VALIDATION ==="

# Check encryption implementation
if [[ -f "$MODULE_DIR/libraries/Encryption.php" ]]; then
    if grep -q "AES-256-GCM" "$MODULE_DIR/libraries/Encryption.php"; then
        pass "Strong encryption algorithm implemented (AES-256-GCM)"
    else
        critical "Weak or missing encryption algorithm"
    fi
    
    if grep -q "random_bytes" "$MODULE_DIR/libraries/Encryption.php"; then
        pass "Cryptographically secure random number generation"
    else
        high "Weak random number generation detected"
    fi
else
    critical "Encryption library missing"
fi

# Check OAuth implementation
OAUTH_FILES=$(find "$MODULE_DIR" -name "*.php" -exec grep -l "oauth\|OAuth" {} \; 2>/dev/null | wc -l)
if [[ $OAUTH_FILES -gt 0 ]]; then
    pass "OAuth implementation found in $OAUTH_FILES files"
    
    # Check for PKCE implementation
    PKCE_IMPL=$(grep -r "code_challenge\|code_verifier" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
    if [[ $PKCE_IMPL -gt 0 ]]; then
        pass "PKCE (Proof Key for Code Exchange) implemented"
    else
        medium "PKCE not implemented - consider for enhanced security"
    fi
else
    critical "OAuth implementation not found"
fi

# Check input validation
VALIDATION_PATTERNS=$(grep -r "filter_var\|htmlspecialchars\|strip_tags\|mysqli_real_escape_string" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
if [[ $VALIDATION_PATTERNS -gt 10 ]]; then
    pass "Comprehensive input validation implemented"
elif [[ $VALIDATION_PATTERNS -gt 5 ]]; then
    medium "Basic input validation implemented"
else
    high "Insufficient input validation"
fi

# Check for hardcoded secrets
HARDCODED_SECRETS=$(grep -r -i -E "(password|secret|key|token).*=.*['\"][^'\"]*['\"]" "$MODULE_DIR" --include="*.php" | grep -v "// " | grep -v "/\*" | wc -l)
if [[ $HARDCODED_SECRETS -gt 0 ]]; then
    critical "Potential hardcoded secrets found: $HARDCODED_SECRETS instances"
else
    pass "No hardcoded secrets detected"
fi

# 4. Performance and Scalability Validation
echo ""
log "=== PERFORMANCE AND SCALABILITY VALIDATION ==="

# Check for caching implementation
CACHING_IMPL=$(grep -r "cache\|redis" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
if [[ $CACHING_IMPL -gt 5 ]]; then
    pass "Caching strategy implemented"
elif [[ $CACHING_IMPL -gt 0 ]]; then
    medium "Basic caching implemented"
else
    high "No caching strategy detected"
fi

# Check queue implementation
if [[ -f "$MODULE_DIR/cli/queue_processor.php" ]]; then
    pass "Queue processing system implemented"
    
    # Check for queue management features
    if grep -q "priority\|retry\|failed" "$MODULE_DIR/cli/queue_processor.php"; then
        pass "Advanced queue features implemented"
    else
        medium "Basic queue implementation only"
    fi
else
    critical "Queue processing system missing"
fi

# Check database optimization
DB_MIGRATIONS=$(find "$MODULE_DIR/database/migrations" -name "*.sql" 2>/dev/null | wc -l)
if [[ $DB_MIGRATIONS -gt 0 ]]; then
    pass "Database migration system implemented"
    
    # Check for indexes in migrations
    INDEX_COUNT=$(grep -i "INDEX\|KEY" "$MODULE_DIR/database/migrations/"*.sql 2>/dev/null | wc -l)
    if [[ $INDEX_COUNT -gt 5 ]]; then
        pass "Database indexes implemented for performance"
    else
        medium "Limited database optimization detected"
    fi
else
    critical "Database migration system missing"
fi

# 5. Code Quality Validation
echo ""
log "=== CODE QUALITY VALIDATION ==="

# Check for Composer dependencies
if [[ -f "$MODULE_DIR/composer.json" ]]; then
    pass "Composer dependency management implemented"
    
    # Check for development vs production dependencies
    if grep -q "require-dev" "$MODULE_DIR/composer.json"; then
        pass "Development dependencies separated"
    else
        low "No development dependencies separation"
    fi
    
    # Check for autoloading
    if grep -q "autoload" "$MODULE_DIR/composer.json"; then
        pass "Autoloading configuration present"
    else
        medium "Missing autoloading configuration"
    fi
else
    high "Composer dependency management missing"
fi

# Check code organization
PHP_FILE_COUNT=$(find "$MODULE_DIR" -name "*.php" | wc -l)
if [[ $PHP_FILE_COUNT -gt 20 ]]; then
    pass "Comprehensive PHP implementation: $PHP_FILE_COUNT files"
elif [[ $PHP_FILE_COUNT -gt 10 ]]; then
    medium "Adequate PHP implementation: $PHP_FILE_COUNT files"
else
    high "Limited PHP implementation: $PHP_FILE_COUNT files"
fi

# Check for namespacing
NAMESPACE_USAGE=$(grep -r "namespace\|use " "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
if [[ $NAMESPACE_USAGE -gt 10 ]]; then
    pass "Proper namespacing implemented"
elif [[ $NAMESPACE_USAGE -gt 0 ]]; then
    medium "Basic namespacing implemented"
else
    low "No namespacing detected"
fi

# 6. Documentation Validation
echo ""
log "=== DOCUMENTATION VALIDATION ==="

# Check for essential documentation
DOCUMENTATION_FILES=(
    "README.md"
    "docs/ADMINISTRATOR_GUIDE.md"
    "docs/CLIENT_USER_GUIDE.md"
    "docs/TROUBLESHOOTING_MANUAL.md"
    "docs/MAINTENANCE_PROCEDURES.md"
)

for doc in "${DOCUMENTATION_FILES[@]}"; do
    if [[ -f "$MODULE_DIR/$doc" ]]; then
        FILE_SIZE=$(stat -c%s "$MODULE_DIR/$doc" 2>/dev/null || echo 0)
        if [[ $FILE_SIZE -gt 1000 ]]; then
            pass "Documentation complete: $doc ($(($FILE_SIZE / 1024))KB)"
        else
            medium "Documentation minimal: $doc"
        fi
    else
        high "Missing documentation: $doc"
    fi
done

# Check for code documentation
PHPDOC_COUNT=$(grep -r "@param\|@return\|@throws" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
if [[ $PHPDOC_COUNT -gt 50 ]]; then
    pass "Comprehensive code documentation"
elif [[ $PHPDOC_COUNT -gt 20 ]]; then
    medium "Basic code documentation"
else
    low "Limited code documentation"
fi

# 7. Configuration Management Validation
echo ""
log "=== CONFIGURATION MANAGEMENT VALIDATION ==="

# Check configuration structure
if [[ -d "$MODULE_DIR/config" ]]; then
    CONFIG_FILES=$(find "$MODULE_DIR/config" -name "*.php" | wc -l)
    if [[ $CONFIG_FILES -gt 0 ]]; then
        pass "Configuration system implemented: $CONFIG_FILES config files"
    else
        medium "Configuration directory empty"
    fi
else
    high "Configuration directory missing"
fi

# Check for environment-specific configuration
ENV_CONFIG=$(grep -r "getenv\|env(" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
if [[ $ENV_CONFIG -gt 0 ]]; then
    pass "Environment-based configuration implemented"
else
    medium "No environment-based configuration detected"
fi

# Check for configuration validation
CONFIG_VALIDATION=$(grep -r "config.*validation\|validate.*config" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
if [[ $CONFIG_VALIDATION -gt 0 ]]; then
    pass "Configuration validation implemented"
else
    low "No configuration validation detected"
fi

# 8. Integration and Compatibility Validation
echo ""
log "=== INTEGRATION AND COMPATIBILITY VALIDATION ==="

# Check Perfex CRM integration hooks
HOOK_USAGE=$(grep -r "hooks()\|add_action\|add_filter" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
if [[ $HOOK_USAGE -gt 5 ]]; then
    pass "Comprehensive Perfex CRM integration"
elif [[ $HOOK_USAGE -gt 0 ]]; then
    medium "Basic Perfex CRM integration"
else
    critical "No Perfex CRM integration detected"
fi

# Check for menu integration
MENU_INTEGRATION=$(grep -r "app_menu\|sidebar" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
if [[ $MENU_INTEGRATION -gt 0 ]]; then
    pass "Admin menu integration implemented"
else
    high "No admin menu integration"
fi

# Check for permission system integration
PERMISSION_USAGE=$(grep -r "has_permission\|tblpermissions" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
if [[ $PERMISSION_USAGE -gt 0 ]]; then
    pass "Permission system integration implemented"
else
    high "No permission system integration"
fi

# 9. Client Portal Validation
echo ""
log "=== CLIENT PORTAL VALIDATION ==="

if [[ -d "$MODULE_DIR/client_portal" ]]; then
    pass "Client portal directory exists"
    
    # Check for Vue.js implementation
    if [[ -f "$MODULE_DIR/client_portal/package.json" ]]; then
        if grep -q "vue" "$MODULE_DIR/client_portal/package.json"; then
            pass "Vue.js client portal implemented"
        else
            medium "Client portal missing Vue.js"
        fi
    else
        medium "Client portal missing package.json"
    fi
    
    # Check for built assets
    if [[ -d "$MODULE_DIR/client_portal/dist" ]]; then
        ASSET_COUNT=$(find "$MODULE_DIR/client_portal/dist" -name "*.js" -o -name "*.css" | wc -l)
        if [[ $ASSET_COUNT -gt 0 ]]; then
            pass "Client portal assets built: $ASSET_COUNT files"
        else
            high "Client portal assets not built"
        fi
    else
        high "Client portal build directory missing"
    fi
else
    high "Client portal not implemented"
fi

# 10. Deployment Readiness Validation
echo ""
log "=== DEPLOYMENT READINESS VALIDATION ==="

# Check for installation scripts
if [[ -f "$MODULE_DIR/scripts/install.sh" && -x "$MODULE_DIR/scripts/install.sh" ]]; then
    pass "Installation script ready"
else
    critical "Installation script missing or not executable"
fi

# Check for deployment documentation
if [[ -f "$MODULE_DIR/PRODUCTION_DEPLOYMENT_PACKAGE.md" ]]; then
    pass "Deployment documentation available"
else
    high "Deployment documentation missing"
fi

# Check for version tracking
if [[ -f "$MODULE_DIR/VERSION" ]]; then
    VERSION=$(cat "$MODULE_DIR/VERSION")
    if [[ "$VERSION" =~ ^[0-9]+\.[0-9]+\.[0-9]+$ ]]; then
        pass "Version properly formatted: $VERSION"
    else
        medium "Version format irregular: $VERSION"
    fi
else
    medium "Version file missing"
fi

# Check for backup procedures
BACKUP_SCRIPTS=$(find "$MODULE_DIR/scripts" -name "*backup*" -o -name "*restore*" 2>/dev/null | wc -l)
if [[ $BACKUP_SCRIPTS -gt 0 ]]; then
    pass "Backup procedures implemented"
else
    medium "No backup procedures detected"
fi

# Calculate Production Readiness Score
echo ""
log "=== CALCULATING PRODUCTION READINESS SCORE ==="

TOTAL_CHECKS=100  # Approximate number of checks performed
TOTAL_FAILURES=$((CRITICAL_FAILURES + HIGH_FAILURES + MEDIUM_FAILURES + LOW_FAILURES))
PASS_COUNT=$((TOTAL_CHECKS - TOTAL_FAILURES))
READINESS_SCORE=$(((PASS_COUNT * 100) / TOTAL_CHECKS))

# Determine readiness status
if [[ $CRITICAL_FAILURES -gt 0 ]]; then
    READINESS_STATUS="NOT READY"
    READINESS_COLOR="${RED}"
elif [[ $HIGH_FAILURES -gt 5 ]]; then
    READINESS_STATUS="NEEDS WORK"
    READINESS_COLOR="${YELLOW}"
elif [[ $HIGH_FAILURES -gt 0 || $MEDIUM_FAILURES -gt 10 ]]; then
    READINESS_STATUS="ALMOST READY"
    READINESS_COLOR="${YELLOW}"
else
    READINESS_STATUS="PRODUCTION READY"
    READINESS_COLOR="${GREEN}"
fi

# Generate final report
echo ""
echo "┌─────────────────────────────────────────────────────────────────────────────┐" | tee -a "$REPORT_FILE"
echo "│                      PRODUCTION READINESS VALIDATION REPORT                │" | tee -a "$REPORT_FILE"
echo "├─────────────────────────────────────────────────────────────────────────────┤" | tee -a "$REPORT_FILE"
echo "│ Module: Desk-Moloni v3.0                                                   │" | tee -a "$REPORT_FILE"
echo "│ Validation Date: $(date)                                    │" | tee -a "$REPORT_FILE"
echo "│ Report File: $REPORT_FILE                                                  │" | tee -a "$REPORT_FILE"
echo "├─────────────────────────────────────────────────────────────────────────────┤" | tee -a "$REPORT_FILE"
printf "│ Readiness Score: %-8s │ Status: %-12s │ Total Checks: %-6s    │\n" "${READINESS_SCORE}%" "$READINESS_STATUS" "$TOTAL_CHECKS" | tee -a "$REPORT_FILE"
echo "├─────────────────────────────────────────────────────────────────────────────┤" | tee -a "$REPORT_FILE"
printf "│ Critical Issues: %-6s │ High Issues: %-6s │ Medium Issues: %-6s   │\n" "$CRITICAL_FAILURES" "$HIGH_FAILURES" "$MEDIUM_FAILURES" | tee -a "$REPORT_FILE"
printf "│ Low Issues: %-10s │ Pass Count: %-8s │ Fail Count: %-8s    │\n" "$LOW_FAILURES" "$PASS_COUNT" "$TOTAL_FAILURES" | tee -a "$REPORT_FILE"
echo "└─────────────────────────────────────────────────────────────────────────────┘" | tee -a "$REPORT_FILE"

echo "" | tee -a "$REPORT_FILE"

# Production readiness recommendations
echo "PRODUCTION READINESS ASSESSMENT:" | tee -a "$REPORT_FILE"
echo "===============================" | tee -a "$REPORT_FILE"

if [[ $CRITICAL_FAILURES -gt 0 ]]; then
    echo "🚨 CRITICAL: $CRITICAL_FAILURES critical issues must be resolved before production deployment" | tee -a "$REPORT_FILE"
    echo "   - Review and fix all critical security, functionality, and integration issues" | tee -a "$REPORT_FILE"
    echo "   - Complete missing core components" | tee -a "$REPORT_FILE"
    echo "   - Implement essential security measures" | tee -a "$REPORT_FILE"
fi

if [[ $HIGH_FAILURES -gt 0 ]]; then
    echo "⚠️  HIGH: $HIGH_FAILURES high-priority issues should be addressed" | tee -a "$REPORT_FILE"
    echo "   - Enhance security implementations" | tee -a "$REPORT_FILE"
    echo "   - Complete missing documentation" | tee -a "$REPORT_FILE"
    echo "   - Improve test coverage" | tee -a "$REPORT_FILE"
fi

if [[ $MEDIUM_FAILURES -gt 0 ]]; then
    echo "📋 MEDIUM: $MEDIUM_FAILURES medium-priority improvements recommended" | tee -a "$REPORT_FILE"
    echo "   - Enhance performance optimizations" | tee -a "$REPORT_FILE"
    echo "   - Improve code documentation" | tee -a "$REPORT_FILE"
    echo "   - Add monitoring capabilities" | tee -a "$REPORT_FILE"
fi

if [[ "$READINESS_STATUS" == "PRODUCTION READY" ]]; then
    echo "✅ EXCELLENT: Module is production ready!" | tee -a "$REPORT_FILE"
    echo "   - All critical requirements met" | tee -a "$REPORT_FILE"
    echo "   - Security standards implemented" | tee -a "$REPORT_FILE"
    echo "   - Documentation complete" | tee -a "$REPORT_FILE"
    echo "   - Testing infrastructure in place" | tee -a "$REPORT_FILE"
fi

echo "" | tee -a "$REPORT_FILE"
echo "NEXT STEPS:" | tee -a "$REPORT_FILE"
echo "1. Address all critical and high-priority issues" | tee -a "$REPORT_FILE"
echo "2. Perform final security audit" | tee -a "$REPORT_FILE"
echo "3. Complete performance testing" | tee -a "$REPORT_FILE"
echo "4. Prepare production deployment plan" | tee -a "$REPORT_FILE"
echo "5. Schedule go-live activities" | tee -a "$REPORT_FILE"

echo ""
echo "========================================================================"
echo -e "Production readiness validation completed!"
echo -e "Readiness Status: ${READINESS_COLOR}$READINESS_STATUS${NC}"
echo -e "Score: $READINESS_SCORE% | Critical: $CRITICAL_FAILURES | High: $HIGH_FAILURES | Medium: $MEDIUM_FAILURES"
echo "Report saved to: $REPORT_FILE"
echo "========================================================================"

# Exit with appropriate code
if [[ $CRITICAL_FAILURES -gt 0 ]]; then
    exit 1
elif [[ $HIGH_FAILURES -gt 5 ]]; then
    exit 2
else
    exit 0
fi