#!/usr/bin/env bash
source "$GIT_CONFIG/git.paths.conf"
set -euo pipefail

# Universal project root detection (zsh-safe)
PROJECT_ROOT="$(cd "$(dirname "$(realpath "$0")")/.." && pwd)"


log() {
    printf "[PATH-SYNC] %s\n" "$1"
}

log "Project root detected: $PROJECT_ROOT"


# ----------------------------------------
# 1. Ensure SSOT exists
# ----------------------------------------
if [[ ! -f "$SSOT" ]]; then
    log "SSOT missing — creating $SSOT"

    mkdir -p "$PROJECT_ROOT/config"

    cat > "$SSOT" << EOF
# Auto-detect project root
GIT_ROOT="$PROJECT_ROOT"

GIT_BIN="\$GIT_ROOT/bin"
GIT_CONFIG="\$GIT_ROOT/config"
GIT_DOCS="\$GIT_ROOT/docs"
GIT_CODE="\$GIT_ROOT/code"
GIT_ARCH="\$GIT_ROOT/arch"
GIT_DATA="\$GIT_ROOT/data"
GIT_CHUNKS="\$GIT_DATA/chunks64"
GIT_AUDIT="\$GIT_ROOT/audit"
GIT_META="\$GIT_ROOT/git.utility.meta"
EOF

    log "SSOT created."
else
    log "SSOT found: $SSOT"
fi

# ----------------------------------------
# 2. Insert SSOT loader into all .sh files
# ----------------------------------------
insert_loader() {
    local file="$1"

    # Skip bundles and binary files
    if [[ "$file" == *.64 ]]; then return; fi
    if file "$file" | grep -q "binary"; then return; fi

    # Only modify shell scripts
    if [[ "$file" != *.sh ]]; then return; fi

    # Remove old loader lines

    # Insert loader after shebang
        NR==1 && /^#!/ {
            print $0
            print loader
            next
        }
        { print }
    ' "$file" > "$file.tmp"

    mv "$file.tmp" "$file"

    log "Inserted SSOT loader into: $file"
}

export -f insert_loader

find "$PROJECT_ROOT" -type f -name "*.sh" -exec bash -c 'insert_loader "$0"' {} \;

# ----------------------------------------
# 3. Remove hard-coded paths
# ----------------------------------------
remove_hardcoded_paths() {
    local file="$1"

    if [[ "$file" == *.64 ]]; then return; fi
    if file "$file" | grep -q "binary"; then return; fi

    sed -i '' \
        -e "s|GIT_ROOT[a-zA-Z0-9_/.-]*|GIT_ROOT|g" \
        -e "s|$PROJECT_ROOT|GIT_ROOT|g" \
        "$file"

    log "Removed hard-coded paths from: $file"
}

export -f remove_hardcoded_paths

find "$PROJECT_ROOT" -type f -exec bash -c 'remove_hardcoded_paths "$0"' {} \;

# ----------------------------------------
# 4. Confirm no hard-coded paths remain
# ----------------------------------------
log "Scanning for remaining hard-coded paths..."

errors=0

scan_file() {
    local file="$1"

    if grep -E "GIT_ROOT|/home/|/mnt/" "$file" >/dev/null 2>&1; then
        echo "[ERROR] Hard-coded path found in: $file"
        errors=$((errors+1))
    fi
}

export -f scan_file

find "$PROJECT_ROOT" -type f -exec bash -c 'scan_file "$0"' {} \;

if (( errors > 0 )); then
    echo "[FAIL] Path sync failed — fix errors above."
    exit 1
fi

echo "[OK] All paths validated — no hard-coded paths remain."
log "Path synchronization complete."

