#!/bin/bash
# Template Version: 8 | ContextKit: 0.1.0 | Updated: 2025-09-16

# MergePreserve.sh - Intelligent template merging with customization preservation
# Automatically merges template updates while preserving user customizations

# ⚠️ FOR DEVELOPERS: Do not edit this file - changes will be overwritten during ContextKit updates.
# Report bugs: https://github.com/FlineDev/ContextKit/issues

## Purpose
# - Merge template updates while preserving "👩‍💻 DEVELOPER CUSTOMIZATIONS" sections
# - Handle files without customization sections (direct replacement)
# - Detect meaningful vs boilerplate customizations for safe replacement
# - Create backups before any modification

set -e

###########################################
# Executable Permission Helper
###########################################
ensure_executable_permissions() {
    local file="$1"

    # Make shell scripts executable
    if [[ "$file" == *.sh ]]; then
        chmod +x "$file"
        echo "  🔧 Made executable: $(basename "$file")"
    fi
}

# Usage: ./MergePreserve.sh <template_file> <target_file>
if [ $# -ne 2 ]; then
    echo "Usage: $0 <template_file> <target_file>"
    echo ""
    echo "Merges template_file into target_file while preserving customizations."
    echo "Automatically detects customization sections and preserves user content."
    exit 1
fi

TEMPLATE_FILE="$1"
TARGET_FILE="$2"

# Validation
if [ ! -f "$TEMPLATE_FILE" ]; then
    echo "❌ ERROR: Template file not found: $TEMPLATE_FILE"
    exit 1
fi

if [ ! -f "$TARGET_FILE" ]; then
    echo "📄 NEW: Copying new file $TEMPLATE_FILE → $TARGET_FILE"
    # Create parent directories if they don't exist
    mkdir -p "$(dirname "$TARGET_FILE")"
    cp "$TEMPLATE_FILE" "$TARGET_FILE"
    ensure_executable_permissions "$TARGET_FILE"
    exit 0
fi

###########################################
# Customization Detection
###########################################
find_customization_section() {
    local file="$1"
    grep -n "👩‍💻 DEVELOPER CUSTOMIZATIONS" "$file" 2>/dev/null | head -1 | cut -d: -f1 || echo "0"
}

has_meaningful_customizations() {
    local file="$1"
    local separator_line="$2"

    if [ "$separator_line" -eq 0 ]; then
        return 1  # No customization section
    fi

    # Count non-empty, non-comment lines after separator
    local total_lines=$(wc -l < "$file")
    local content_lines=$(tail -n +$((separator_line + 1)) "$file" | \
        grep -v '^[[:space:]]*$' | \
        grep -v '^[[:space:]]*<!--' | \
        grep -v '^[[:space:]]*#' | \
        grep -c '^' || echo "0")

    # Consider meaningful if more than 3 lines of actual content
    [ "$content_lines" -gt 3 ]
}

###########################################
# Merge Logic
###########################################
merge_with_preservation() {
    local template="$1"
    local target="$2"

    local target_separator=$(find_customization_section "$target")
    local template_separator=$(find_customization_section "$template")

    # If target has no customization section, direct replacement
    if [ "$target_separator" -eq 0 ]; then
        echo "🔄 REPLACE: No customization section found"
        cp "$template" "$target"
        ensure_executable_permissions "$target"
        return 0
    fi

    # Check if customizations are meaningful
    if ! has_meaningful_customizations "$target" "$target_separator"; then
        echo "🔄 REPLACE: Only boilerplate customizations found"
        cp "$template" "$target"
        ensure_executable_permissions "$target"
        return 0
    fi

    # Preserve meaningful customizations
    echo "🔀 MERGE: Preserving user customizations from line $target_separator"

    if [ "$template_separator" -eq 0 ]; then
        # Template has no customization section - append user customizations
        echo "⚠️  WARNING: Template no longer has customization section"
        echo "    Your customizations will be preserved but consider reviewing."
        {
            cat "$template"
            echo ""
            echo "════════════════════════════════════════════════════════════════════════════════"
            echo "👩‍💻 DEVELOPER CUSTOMIZATIONS - PRESERVED FROM PREVIOUS VERSION"
            echo "════════════════════════════════════════════════════════════════════════════════"
            tail -n +$((target_separator + 1)) "$target"
        } > "$target.tmp" && mv "$target.tmp" "$target"
        ensure_executable_permissions "$target"
    else
        # Both have customization sections - standard merge
        {
            head -n "$template_separator" "$template"
            tail -n +$((target_separator + 1)) "$target"
        } > "$target.tmp" && mv "$target.tmp" "$target"
        ensure_executable_permissions "$target"
    fi
}

###########################################
# Main Execution
###########################################
main() {
    echo "🔄 Processing: $(basename "$TARGET_FILE")"

    # Perform merge with preservation
    merge_with_preservation "$TEMPLATE_FILE" "$TARGET_FILE"

    echo "✅ SUCCESS: Merged $(basename "$TEMPLATE_FILE") → $(basename "$TARGET_FILE")"
    echo ""
}

# Execute main function
main "$@"
