#!/bin/bash

# Check if the checkout is switching branches (flag $3 == 1)
if [[ "$3" -eq 0 ]]; then
    echo "🔹 File checkout detected. Skipping post-checkout hook."
    exit 0
fi

# Get the list of submodules
submodules=$(git config --file .gitmodules --get-regexp path | awk '{print $2}')


# Get the current branch name
current_branch=$(git rev-parse --abbrev-ref HEAD)

REPO_ROOT=$(git rev-parse --show-toplevel)
# Check if the branch exists in the remote to determine if it's a new branch
if ! git ls-remote --exit-code --heads origin "$current_branch" >/dev/null 2>&1; then
    echo "🛠 You have created a new branch: $current_branch"

    # Loop through all submodules and prompt for branch creation
    for submodule in $submodules; do
        echo "🔎 Checking submodule: $submodule"
        # Change directory to the submodule
        cd "$REPO_ROOT/$submodule" || { echo "❌ Failed to enter submodule: $submodule"; exit 1; }
        # Check if the branch already exists in the commanding submodule
        if git show-ref --quiet --heads "$current_branch"; then
            echo "🔹 Branch $current_branch already exists in submodule $submodule. Skipping."
        else
            echo "🆕 Branch does NOT exist in $submodule. Prompting user..."
            # Ask the user if they want to create the branch in the submodule
            read -p "Do you want to create the same branch ($current_branch) in submodule $submodule? [y/N]: " response < /dev/tty
            if [[ "$response" =~ ^[Yy]$ ]]; then
                git checkout -b "$current_branch"
                echo "✅ Branch $current_branch created in submodule $submodule."
            fi
        fi

        # Return to the root of the main repository
        cd - >/dev/null
    done
else
    echo "🔄 Branch switch detected. Running submodule update check..."
    echo "🔍 Checking for local changes or uncommitted submodule changes before checkout..."
    has_changes=0
    for submodule in $submodules; do
        # Check if the submodule has local modifications
        if [[ -n $(git -C "$submodule" status --porcelain) ]]; then
            echo "⚠️ WARNING: Local changes detected in submodule: $submodule"
            echo "❌ Submodule will NOT be updated. Make sure TO UPDATE THE SUBMODULE MANUALLY AFTER as this hook won't do it for you!"
            echo "❌ This is NOT recommended. Please commit or stash your changes in submodules before switching branches."
            has_changes=1
        fi

        # Check if the submodule is ahead (i.e., it has committed changes not reflected in the super repo)
        submodule_commit=$(git -C "$submodule" rev-parse HEAD)
        super_repo_commit=$(git ls-tree HEAD "$submodule" | awk '{print $3}')
        
        if [[ "$submodule_commit" != "$super_repo_commit" ]]; then
            echo "⚠️ WARNING: Submodule '$submodule' is on commit $submodule_commit but super repo references commit $super_repo_commit."
            echo "⚠️ Submodule update will proceed and would override the submodule reference."
        fi

    done

    # If no changes and no uncommitted submodules, update submodules
    if [[ $has_changes -eq 0 ]]; then
        echo "✅ No local changes or uncommitted submodules detected. Updating submodules..."
        git submodule update --init --recursive
    else
        echo "⏩ Skipping submodule update due to local changes or uncommitted submodule commits."
        echo "⚠️ Please ensure your submodules are correctly updated after switching branches!"
    fi
fi