source "$(dirname "${BASH_SOURCE[0]}")/env-init.sh"
#!/bin/bash
# system/scripts/fix-system.sh

# 1. Standardize all .sh files (Golden Rule)
# We look for all scripts in system/scripts/ and apps/*/admin/
find . -name "*.sh" -not -name "env-init.sh" | while read -r script; do
    echo "Refactoring $script..."
    # Create temp file with the source line prepended
    echo 'source "$(dirname "${BASH_SOURCE[0]}")/env-init.sh"' > "$script.new"
    # Skip the existing shebang if it exists, otherwise keep content
    grep -v '^source' "$script" >> "$script.new"
    mv "$script.new" "$script"
    chmod +x "$script"
done

# 2. Structural Audit
echo "--- Running Structural Audit ---"
ROOT=$(realpath "$(dirname "${BASH_SOURCE[0]}")/../..")
REQUIRED=("admin" "css" "data/sql" "docs" "images" "js" "php")

for app in "$ROOT/apps/"*; do
    [ -d "$app" ] || continue
    for folder in "${REQUIRED[@]}"; do
        if [ ! -d "$app/$folder" ]; then
            echo "[FIXING] Creating missing folder: $app/$folder"
            mkdir -p "$app/$folder"
        fi
    done
done
