#!/bin/bash

# Desk-Moloni v3.0 Performance Analysis and Report Generator
# 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-performance-report-$(date +%Y%m%d-%H%M%S).html"
JSON_REPORT="/tmp/desk-moloni-performance-data-$(date +%Y%m%d-%H%M%S).json"
PERFEX_ROOT=""

# Performance thresholds
SYNC_TIME_THRESHOLD=30      # seconds
SUCCESS_RATE_THRESHOLD=99.5 # percentage
API_RESPONSE_THRESHOLD=5    # seconds
QUEUE_RATE_THRESHOLD=1000   # tasks per hour
MEMORY_THRESHOLD=80         # percentage
CPU_THRESHOLD=80            # percentage

# Functions
log() {
    echo -e "${GREEN}[PERF]${NC} $1"
}

warning() {
    echo -e "${YELLOW}[WARN]${NC} $1"
}

error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

# Find Perfex root directory
find_perfex_root() {
    local current_dir="$MODULE_DIR"
    while [[ "$current_dir" != "/" ]]; do
        if [[ -f "$current_dir/application/config/app.php" ]]; then
            PERFEX_ROOT="$current_dir"
            return 0
        fi
        current_dir="$(dirname "$current_dir")"
    done
    return 1
}

# Performance banner
echo "========================================================================"
echo "                  DESK-MOLONI v3.0 PERFORMANCE REPORT"
echo "========================================================================"
echo "Report File: $REPORT_FILE"
echo "JSON Data: $JSON_REPORT"
echo "Analysis Date: $(date)"
echo ""

log "Starting comprehensive performance analysis..."

# Find Perfex installation
if ! find_perfex_root; then
    error "Could not find Perfex CRM installation directory"
    exit 1
fi

log "Perfex CRM root found: $PERFEX_ROOT"

# Initialize HTML report
cat > "$REPORT_FILE" << 'EOF'
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Desk-Moloni Performance Report</title>
    <style>
        body { font-family: Arial, sans-serif; margin: 20px; background-color: #f5f5f5; }
        .container { max-width: 1200px; margin: 0 auto; background: white; padding: 20px; border-radius: 8px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }
        .header { text-align: center; border-bottom: 3px solid #007cba; padding-bottom: 20px; margin-bottom: 30px; }
        .metric-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); gap: 20px; margin: 20px 0; }
        .metric-card { background: #f8f9fa; padding: 20px; border-radius: 8px; border-left: 4px solid #007cba; }
        .metric-value { font-size: 2em; font-weight: bold; color: #007cba; }
        .metric-label { color: #666; font-size: 0.9em; margin-top: 5px; }
        .status-excellent { color: #28a745; }
        .status-good { color: #17a2b8; }
        .status-warning { color: #ffc107; }
        .status-critical { color: #dc3545; }
        .chart-container { margin: 20px 0; padding: 20px; background: #f8f9fa; border-radius: 8px; }
        .table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        .table th, .table td { padding: 12px; text-align: left; border-bottom: 1px solid #ddd; }
        .table th { background-color: #007cba; color: white; }
        .recommendation { background: #e7f3ff; padding: 15px; margin: 10px 0; border-radius: 5px; border-left: 4px solid #007cba; }
        .section { margin: 30px 0; }
        .section h2 { color: #007cba; border-bottom: 2px solid #007cba; padding-bottom: 10px; }
    </style>
</head>
<body>
    <div class="container">
        <div class="header">
            <h1>🚀 Desk-Moloni v3.0 Performance Report</h1>
            <p>Generated on <strong>__REPORT_DATE__</strong></p>
        </div>
EOF

# Initialize JSON report
cat > "$JSON_REPORT" << EOF
{
    "report_meta": {
        "version": "3.0.0",
        "generated_at": "$(date -Iseconds)",
        "module_path": "$MODULE_DIR",
        "perfex_root": "$PERFEX_ROOT"
    },
    "metrics": {},
    "recommendations": [],
    "status": "unknown"
}
EOF

# 1. System Information
echo ""
log "=== COLLECTING SYSTEM INFORMATION ==="

SYSTEM_INFO=$(cat << EOF
{
    "php_version": "$(php -r 'echo PHP_VERSION;')",
    "memory_limit": "$(php -r 'echo ini_get("memory_limit");')",
    "max_execution_time": "$(php -r 'echo ini_get("max_execution_time");')",
    "server_software": "${SERVER_SOFTWARE:-Unknown}",
    "operating_system": "$(uname -s -r)",
    "cpu_cores": "$(nproc 2>/dev/null || echo 'Unknown')",
    "total_memory": "$(free -h | awk '/^Mem:/ {print $2}' 2>/dev/null || echo 'Unknown')"
}
EOF
)

info "System Information collected"

# 2. Database Performance Analysis
echo ""
log "=== ANALYZING DATABASE PERFORMANCE ==="

DB_METRICS=""
if command -v mysql > /dev/null 2>&1; then
    # Try to connect to database and get metrics
    DB_METRICS=$(cat << 'EOF'
{
    "connection_test": "attempting",
    "table_sizes": {},
    "query_performance": {},
    "index_usage": {}
}
EOF
    )
    
    # Check if we can determine database connection details
    if [[ -f "$PERFEX_ROOT/application/config/database.php" ]]; then
        info "Database configuration found"
        
        # Get table sizes (basic estimation)
        TABLE_COUNT=$(find "$MODULE_DIR/database" -name "*.sql" | wc -l)
        DB_METRICS=$(echo "$DB_METRICS" | jq ".table_count = $TABLE_COUNT")
    else
        warning "Database configuration not accessible"
    fi
else
    warning "MySQL client not available for database analysis"
    DB_METRICS='{"status": "unavailable", "reason": "mysql client not found"}'
fi

info "Database metrics collected"

# 3. File System Performance
echo ""
log "=== ANALYZING FILE SYSTEM PERFORMANCE ==="

# Calculate directory sizes
MODULE_SIZE=$(du -sb "$MODULE_DIR" 2>/dev/null | cut -f1 || echo "0")
UPLOADS_SIZE=0
if [[ -d "$PERFEX_ROOT/uploads/desk_moloni" ]]; then
    UPLOADS_SIZE=$(du -sb "$PERFEX_ROOT/uploads/desk_moloni" 2>/dev/null | cut -f1 || echo "0")
fi

# Count files
TOTAL_FILES=$(find "$MODULE_DIR" -type f | wc -l)
PHP_FILES=$(find "$MODULE_DIR" -name "*.php" | wc -l)
JS_FILES=$(find "$MODULE_DIR" -name "*.js" | wc -l)
CSS_FILES=$(find "$MODULE_DIR" -name "*.css" | wc -l)

FILESYSTEM_METRICS=$(cat << EOF
{
    "module_size_bytes": $MODULE_SIZE,
    "uploads_size_bytes": $UPLOADS_SIZE,
    "total_files": $TOTAL_FILES,
    "php_files": $PHP_FILES,
    "js_files": $JS_FILES,
    "css_files": $CSS_FILES,
    "module_size_mb": $(echo "scale=2; $MODULE_SIZE/1024/1024" | bc -l 2>/dev/null || echo "0")
}
EOF
)

info "File system metrics collected"

# 4. Code Quality Metrics
echo ""
log "=== ANALYZING CODE QUALITY ==="

# Lines of code analysis
TOTAL_LOC=0
PHP_LOC=0
JS_LOC=0

if [[ $PHP_FILES -gt 0 ]]; then
    PHP_LOC=$(find "$MODULE_DIR" -name "*.php" -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}' || echo "0")
fi

if [[ $JS_FILES -gt 0 ]]; then
    JS_LOC=$(find "$MODULE_DIR" -name "*.js" -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}' || echo "0")
fi

TOTAL_LOC=$((PHP_LOC + JS_LOC))

# Test coverage estimation
TEST_FILES=$(find "$MODULE_DIR" -name "*Test.php" | wc -l)
TEST_LOC=0
if [[ $TEST_FILES -gt 0 ]]; then
    TEST_LOC=$(find "$MODULE_DIR" -name "*Test.php" -exec wc -l {} + 2>/dev/null | tail -1 | awk '{print $1}' || echo "0")
fi

CODE_METRICS=$(cat << EOF
{
    "total_lines_of_code": $TOTAL_LOC,
    "php_lines_of_code": $PHP_LOC,
    "js_lines_of_code": $JS_LOC,
    "test_files": $TEST_FILES,
    "test_lines_of_code": $TEST_LOC,
    "test_coverage_estimate": $(echo "scale=2; $TEST_LOC*100/$PHP_LOC" | bc -l 2>/dev/null || echo "0")
}
EOF
)

info "Code quality metrics collected"

# 5. Performance Simulation
echo ""
log "=== RUNNING PERFORMANCE SIMULATION ==="

# Simulate basic performance tests
START_TIME=$(date +%s.%N)

# Test file loading performance
if [[ -f "$MODULE_DIR/desk_moloni.php" ]]; then
    php -l "$MODULE_DIR/desk_moloni.php" > /dev/null 2>&1
fi

# Test autoloader performance
if [[ -f "$MODULE_DIR/vendor/autoload.php" ]]; then
    php -r "require_once '$MODULE_DIR/vendor/autoload.php';" > /dev/null 2>&1
fi

END_TIME=$(date +%s.%N)
LOAD_TIME=$(echo "$END_TIME - $START_TIME" | bc -l 2>/dev/null || echo "0")

# Memory usage estimation
MEMORY_USAGE=$(php -r "
    \$start = memory_get_usage();
    if (file_exists('$MODULE_DIR/vendor/autoload.php')) {
        require_once '$MODULE_DIR/vendor/autoload.php';
    }
    echo memory_get_usage() - \$start;
" 2>/dev/null || echo "0")

PERFORMANCE_METRICS=$(cat << EOF
{
    "module_load_time": "$LOAD_TIME",
    "estimated_memory_usage": $MEMORY_USAGE,
    "memory_usage_mb": $(echo "scale=2; $MEMORY_USAGE/1024/1024" | bc -l 2>/dev/null || echo "0")
}
EOF
)

info "Performance simulation completed"

# 6. Security Performance
echo ""
log "=== ANALYZING SECURITY PERFORMANCE ==="

# Check for security-related files
SECURITY_FILES=0
[[ -f "$MODULE_DIR/libraries/Encryption.php" ]] && ((SECURITY_FILES++))
[[ -f "$MODULE_DIR/config/security.php" ]] && ((SECURITY_FILES++))

# Check for security patterns in code
ENCRYPTION_USAGE=$(grep -r "encrypt\|decrypt" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)
OAUTH_USAGE=$(grep -r "oauth\|OAuth" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l)

SECURITY_METRICS=$(cat << EOF
{
    "security_files": $SECURITY_FILES,
    "encryption_usage_count": $ENCRYPTION_USAGE,
    "oauth_implementation_count": $OAUTH_USAGE,
    "security_score": $(echo "scale=2; ($SECURITY_FILES + $ENCRYPTION_USAGE + $OAUTH_USAGE) * 10" | bc -l 2>/dev/null || echo "0")
}
EOF
)

info "Security performance metrics collected"

# 7. Generate Performance Score
echo ""
log "=== CALCULATING PERFORMANCE SCORE ==="

# Calculate overall performance score
PERFORMANCE_SCORE=0

# File organization score (0-25 points)
if [[ $TOTAL_FILES -lt 100 && $MODULE_SIZE -lt 10000000 ]]; then
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 25))
elif [[ $TOTAL_FILES -lt 200 && $MODULE_SIZE -lt 50000000 ]]; then
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 20))
else
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 10))
fi

# Code quality score (0-25 points)
if [[ $TEST_FILES -gt 10 && $PHP_FILES -gt 0 ]]; then
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 25))
elif [[ $TEST_FILES -gt 5 ]]; then
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 15))
else
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 5))
fi

# Security implementation score (0-25 points)
if [[ $SECURITY_FILES -gt 1 && $ENCRYPTION_USAGE -gt 5 ]]; then
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 25))
elif [[ $SECURITY_FILES -gt 0 || $ENCRYPTION_USAGE -gt 0 ]]; then
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 15))
else
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 5))
fi

# Architecture score (0-25 points)
if [[ -f "$MODULE_DIR/composer.json" && -d "$MODULE_DIR/vendor" ]]; then
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 25))
elif [[ -f "$MODULE_DIR/composer.json" ]]; then
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 15))
else
    PERFORMANCE_SCORE=$((PERFORMANCE_SCORE + 10))
fi

# Determine performance grade
if [[ $PERFORMANCE_SCORE -ge 90 ]]; then
    PERFORMANCE_GRADE="A+"
    GRADE_COLOR="status-excellent"
elif [[ $PERFORMANCE_SCORE -ge 80 ]]; then
    PERFORMANCE_GRADE="A"
    GRADE_COLOR="status-excellent"
elif [[ $PERFORMANCE_SCORE -ge 70 ]]; then
    PERFORMANCE_GRADE="B"
    GRADE_COLOR="status-good"
elif [[ $PERFORMANCE_SCORE -ge 60 ]]; then
    PERFORMANCE_GRADE="C"
    GRADE_COLOR="status-warning"
else
    PERFORMANCE_GRADE="D"
    GRADE_COLOR="status-critical"
fi

info "Performance score calculated: $PERFORMANCE_SCORE/100 ($PERFORMANCE_GRADE)"

# 8. Compile final JSON report
echo ""
log "=== COMPILING FINAL REPORT ==="

FINAL_JSON=$(cat << EOF
{
    "report_meta": {
        "version": "3.0.0",
        "generated_at": "$(date -Iseconds)",
        "module_path": "$MODULE_DIR",
        "perfex_root": "$PERFEX_ROOT",
        "performance_score": $PERFORMANCE_SCORE,
        "performance_grade": "$PERFORMANCE_GRADE"
    },
    "system_info": $SYSTEM_INFO,
    "database_metrics": $DB_METRICS,
    "filesystem_metrics": $FILESYSTEM_METRICS,
    "code_metrics": $CODE_METRICS,
    "performance_metrics": $PERFORMANCE_METRICS,
    "security_metrics": $SECURITY_METRICS,
    "recommendations": [
        {
            "category": "optimization",
            "priority": "medium",
            "description": "Consider implementing Redis caching for improved performance"
        },
        {
            "category": "monitoring",
            "priority": "high",
            "description": "Set up performance monitoring for production environment"
        },
        {
            "category": "testing",
            "priority": "medium",
            "description": "Increase test coverage for better code quality assurance"
        }
    ]
}
EOF
)

echo "$FINAL_JSON" > "$JSON_REPORT"

# 9. Generate HTML report
log "=== GENERATING HTML REPORT ==="

# Update HTML report with actual data
sed -i "s/__REPORT_DATE__/$(date)/" "$REPORT_FILE"

cat >> "$REPORT_FILE" << EOF
        <div class="section">
            <h2>📊 Performance Overview</h2>
            <div class="metric-grid">
                <div class="metric-card">
                    <div class="metric-value $GRADE_COLOR">$PERFORMANCE_GRADE</div>
                    <div class="metric-label">Performance Grade</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value">$PERFORMANCE_SCORE/100</div>
                    <div class="metric-label">Overall Score</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value">$(echo "scale=1; $MODULE_SIZE/1024/1024" | bc -l 2>/dev/null || echo "0") MB</div>
                    <div class="metric-label">Module Size</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value">$TOTAL_FILES</div>
                    <div class="metric-label">Total Files</div>
                </div>
            </div>
        </div>

        <div class="section">
            <h2>💾 System Information</h2>
            <table class="table">
                <tr><th>Metric</th><th>Value</th><th>Status</th></tr>
                <tr><td>PHP Version</td><td>$(php -r 'echo PHP_VERSION;')</td><td class="status-excellent">✓</td></tr>
                <tr><td>Memory Limit</td><td>$(php -r 'echo ini_get("memory_limit");')</td><td class="status-good">Good</td></tr>
                <tr><td>Max Execution Time</td><td>$(php -r 'echo ini_get("max_execution_time");')s</td><td class="status-good">Good</td></tr>
                <tr><td>Operating System</td><td>$(uname -s -r)</td><td class="status-excellent">✓</td></tr>
            </table>
        </div>

        <div class="section">
            <h2>📁 File System Analysis</h2>
            <div class="metric-grid">
                <div class="metric-card">
                    <div class="metric-value">$PHP_FILES</div>
                    <div class="metric-label">PHP Files</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value">$TEST_FILES</div>
                    <div class="metric-label">Test Files</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value">$(echo "scale=0; $PHP_LOC" | bc -l 2>/dev/null || echo "0")</div>
                    <div class="metric-label">Lines of PHP Code</div>
                </div>
                <div class="metric-card">
                    <div class="metric-value">$(echo "scale=1; $TEST_LOC*100/$PHP_LOC" | bc -l 2>/dev/null || echo "0")%</div>
                    <div class="metric-label">Test Coverage Est.</div>
                </div>
            </div>
        </div>

        <div class="section">
            <h2>🔒 Security Performance</h2>
            <table class="table">
                <tr><th>Security Feature</th><th>Implementation</th><th>Status</th></tr>
                <tr><td>Encryption Library</td><td>$([[ -f "$MODULE_DIR/libraries/Encryption.php" ]] && echo "Implemented" || echo "Not Found")</td><td class="$([[ -f "$MODULE_DIR/libraries/Encryption.php" ]] && echo "status-excellent" || echo "status-warning")">$([[ -f "$MODULE_DIR/libraries/Encryption.php" ]] && echo "✓" || echo "⚠")</td></tr>
                <tr><td>OAuth Implementation</td><td>$OAUTH_USAGE references found</td><td class="status-good">Good</td></tr>
                <tr><td>Input Validation</td><td>$(grep -r "filter_var\|htmlspecialchars" "$MODULE_DIR" --include="*.php" 2>/dev/null | wc -l) patterns found</td><td class="status-good">Good</td></tr>
            </table>
        </div>

        <div class="section">
            <h2>🚀 Performance Recommendations</h2>
            
            <div class="recommendation">
                <h4>💡 Immediate Improvements</h4>
                <ul>
                    <li><strong>Enable OpCache:</strong> Configure PHP OpCache for better performance</li>
                    <li><strong>Database Optimization:</strong> Add proper indexes for query optimization</li>
                    <li><strong>Caching Strategy:</strong> Implement Redis caching for API responses</li>
                </ul>
            </div>

            <div class="recommendation">
                <h4>📈 Long-term Optimizations</h4>
                <ul>
                    <li><strong>Load Testing:</strong> Perform comprehensive load testing</li>
                    <li><strong>Monitoring:</strong> Set up performance monitoring and alerting</li>
                    <li><strong>Code Optimization:</strong> Profile and optimize critical code paths</li>
                </ul>
            </div>

            <div class="recommendation">
                <h4>🔧 Development Best Practices</h4>
                <ul>
                    <li><strong>Test Coverage:</strong> Increase unit test coverage to >80%</li>
                    <li><strong>Code Quality:</strong> Implement static analysis tools</li>
                    <li><strong>Documentation:</strong> Maintain comprehensive API documentation</li>
                </ul>
            </div>
        </div>

        <div class="section">
            <h2>📋 Performance Checklist</h2>
            <table class="table">
                <tr><th>Performance Factor</th><th>Current Status</th><th>Target</th><th>Action Required</th></tr>
                <tr><td>Module Load Time</td><td>${LOAD_TIME}s</td><td>&lt;0.5s</td><td>$([[ $(echo "$LOAD_TIME < 0.5" | bc -l 2>/dev/null) == "1" ]] && echo "✓ Met" || echo "⚠ Optimize")</td></tr>
                <tr><td>Memory Usage</td><td>$(echo "scale=1; $MEMORY_USAGE/1024/1024" | bc -l 2>/dev/null || echo "0") MB</td><td>&lt;64 MB</td><td>$([[ $(echo "$MEMORY_USAGE < 67108864" | bc -l 2>/dev/null) == "1" ]] && echo "✓ Met" || echo "⚠ Optimize")</td></tr>
                <tr><td>File Count</td><td>$TOTAL_FILES files</td><td>&lt;200 files</td><td>$([[ $TOTAL_FILES -lt 200 ]] && echo "✓ Met" || echo "⚠ Reduce")</td></tr>
                <tr><td>Test Coverage</td><td>$(echo "scale=1; $TEST_LOC*100/$PHP_LOC" | bc -l 2>/dev/null || echo "0")%</td><td>&gt;80%</td><td>$([[ $(echo "$TEST_LOC*100/$PHP_LOC > 80" | bc -l 2>/dev/null) == "1" ]] && echo "✓ Met" || echo "⚠ Increase")</td></tr>
            </table>
        </div>

        <div class="section">
            <h2>📊 Benchmark Results</h2>
            <div class="chart-container">
                <h4>Performance Metrics Summary</h4>
                <table class="table">
                    <tr><th>Metric Category</th><th>Score</th><th>Weight</th><th>Contribution</th></tr>
                    <tr><td>File Organization</td><td>$([[ $TOTAL_FILES -lt 100 ]] && echo "25/25" || echo "20/25")</td><td>25%</td><td>$([[ $TOTAL_FILES -lt 100 ]] && echo "Excellent" || echo "Good")</td></tr>
                    <tr><td>Code Quality</td><td>$([[ $TEST_FILES -gt 10 ]] && echo "25/25" || echo "15/25")</td><td>25%</td><td>$([[ $TEST_FILES -gt 10 ]] && echo "Excellent" || echo "Good")</td></tr>
                    <tr><td>Security Implementation</td><td>$([[ $SECURITY_FILES -gt 1 ]] && echo "25/25" || echo "15/25")</td><td>25%</td><td>$([[ $SECURITY_FILES -gt 1 ]] && echo "Excellent" || echo "Good")</td></tr>
                    <tr><td>Architecture</td><td>$([[ -f "$MODULE_DIR/composer.json" ]] && echo "25/25" || echo "10/25")</td><td>25%</td><td>$([[ -f "$MODULE_DIR/composer.json" ]] && echo "Excellent" || echo "Fair")</td></tr>
                </table>
            </div>
        </div>

        <div class="section">
            <h2>🎯 Next Steps</h2>
            <ol>
                <li><strong>Review Performance Score:</strong> Current score is $PERFORMANCE_SCORE/100 ($PERFORMANCE_GRADE)</li>
                <li><strong>Implement Recommendations:</strong> Focus on high-priority optimizations</li>
                <li><strong>Setup Monitoring:</strong> Implement performance monitoring in production</li>
                <li><strong>Schedule Regular Audits:</strong> Run performance analysis monthly</li>
                <li><strong>Load Testing:</strong> Perform comprehensive load testing before production</li>
            </ol>
        </div>

        <div style="text-align: center; margin-top: 40px; padding-top: 20px; border-top: 1px solid #ddd; color: #666;">
            <p>Generated by Desk-Moloni v3.0 Performance Analyzer</p>
            <p>© 2025 Descomplicar®. All rights reserved.</p>
        </div>
    </div>
</body>
</html>
EOF

# 10. Display summary
echo ""
echo "========================================================================"
echo "                      PERFORMANCE ANALYSIS COMPLETE"
echo "========================================================================"
echo ""
printf "Performance Grade: %s\n" "$PERFORMANCE_GRADE"
printf "Overall Score: %d/100\n" "$PERFORMANCE_SCORE"
printf "Module Size: %.1f MB\n" "$(echo "scale=1; $MODULE_SIZE/1024/1024" | bc -l 2>/dev/null || echo "0")"
printf "Total Files: %d\n" "$TOTAL_FILES"
printf "Lines of Code: %d\n" "$TOTAL_LOC"
printf "Test Files: %d\n" "$TEST_FILES"
echo ""
echo "Reports Generated:"
echo "  📊 HTML Report: $REPORT_FILE"
echo "  📋 JSON Data: $JSON_REPORT"
echo ""

# Performance recommendations
echo "🚀 KEY RECOMMENDATIONS:"
if [[ $PERFORMANCE_SCORE -lt 70 ]]; then
    echo "  ⚠️  Performance needs significant improvement"
    echo "  🔧 Focus on code optimization and testing"
elif [[ $PERFORMANCE_SCORE -lt 85 ]]; then
    echo "  ✅ Good performance with room for improvement"
    echo "  📈 Implement caching and monitoring"
else
    echo "  🎉 Excellent performance! Maintain current standards"
    echo "  🔍 Focus on monitoring and continuous optimization"
fi

echo ""
echo "========================================================================"

# Open report in browser if available
if command -v xdg-open > /dev/null 2>&1; then
    log "Opening performance report in browser..."
    xdg-open "$REPORT_FILE" 2>/dev/null &
elif command -v open > /dev/null 2>&1; then
    log "Opening performance report in browser..."
    open "$REPORT_FILE" 2>/dev/null &
fi

# Exit with appropriate code
if [[ $PERFORMANCE_SCORE -lt 60 ]]; then
    exit 1
else
    exit 0
fi