#!/bin/bash

# Check if file path is provided
if [ -z "$1" ]; then
    echo "Usage: $0 <path-to-conflicted-file>"
    echo "Example: $0 sites/default/mixins.less"
    exit 1
fi

FILE="$1"

# Check if file exists
if [ ! -f "$FILE" ]; then
    echo "Error: File '$FILE' not found"
    exit 1
fi

# Check if file has conflict markers
if ! grep -q "<<<<<<< HEAD" "$FILE"; then
    echo "Error: No Git conflict markers found in '$FILE'"
    exit 1
fi

# Get directory and filename
DIR=$(dirname "$FILE")
FILENAME=$(basename "$FILE")
NAME="${FILENAME%.*}"
EXT="${FILENAME##*.}"

# Output files
HEAD_FILE="$DIR/${NAME}-HEAD.${EXT}"
BRANCH_FILE="$DIR/${NAME}-shop-page.${EXT}"

# Extract HEAD version (between <<<<<<< HEAD and =======)
sed -n '/<<<<<<< HEAD/,/=======/p' "$FILE" | sed '1d;$d' > "$HEAD_FILE"

# Extract branch version (between ======= and >>>>>>> shop-page)
sed -n '/=======/,/>>>>>>> shop-page/p' "$FILE" | sed '1d;$d' > "$BRANCH_FILE"

echo "✓ Created: $HEAD_FILE"
echo "✓ Created: $BRANCH_FILE"
echo ""
echo "Now resolve the conflict in your editor."
echo "Make both files identical with your final merged version."
echo ""
read -p "Press ENTER when you're done merging..."

# Check if files are identical
if ! cmp -s "$HEAD_FILE" "$BRANCH_FILE"; then
    echo ""
    echo "⚠ Warning: Files are not identical yet!"
    echo "Differences found:"
    diff "$HEAD_FILE" "$BRANCH_FILE"
    echo ""
    read -p "Continue anyway? (y/N): " CONFIRM
    if [[ ! "$CONFIRM" =~ ^[Yy]$ ]]; then
        echo "Aborted. No changes made to $FILE"
        exit 0
    fi
fi

# Copy the merged version back to original file
cp "$HEAD_FILE" "$FILE"

echo ""
echo "✓ Merged version copied to: $FILE"
echo ""
read -p "Delete temporary files? (Y/n): " DELETE

if [[ ! "$DELETE" =~ ^[Nn]$ ]]; then
    rm "$HEAD_FILE" "$BRANCH_FILE"
    echo "✓ Temporary files deleted"
else
    echo "Temporary files kept: $HEAD_FILE, $BRANCH_FILE"
fi

echo ""
echo "Done! Conflict resolved."
