import os

file_path = 'core/templates/core/voter_advanced_search.html'
with open(file_path, 'r') as f:
    content = f.read()

old_code = """    const bulkCallModal = document.getElementById('bulkCallModal');
    if (bulkCallModal) {
        bulkCallModal.addEventListener('show.bs.modal', function () {
            const container = document.getElementById('selected-voters-call-container');
            container.innerHTML = '';
            checkboxes.forEach(cb => {
                if (cb.checked) {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'selected_voters';
                    input.value = cb.value;
                    container.appendChild(input);
                }
            });
        });
    }"""

new_code = """    const bulkCallModal = document.getElementById('bulkCallModal');
    if (bulkCallModal) {
        bulkCallModal.addEventListener('show.bs.modal', function () {
            const container = document.getElementById('selected-voters-call-container');
            container.innerHTML = '';
            checkboxes.forEach(cb => {
                if (cb.checked) {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'selected_voters';
                    input.value = cb.value;
                    container.appendChild(input);
                }
            });
        });
    }

    const emailModal = document.getElementById('emailModal');
    if (emailModal) {
        emailModal.addEventListener('show.bs.modal', function () {
            const container = document.getElementById('selected-voters-email-container');
            container.innerHTML = '';
            checkboxes.forEach(cb => {
                if (cb.checked) {
                    const input = document.createElement('input');
                    input.type = 'hidden';
                    input.name = 'selected_voters';
                    input.value = cb.value;
                    container.appendChild(input);
                }
            });
        });
    }"""

if old_code in content:
    new_content = content.replace(old_code, new_code)
    with open(file_path, 'w') as f:
        f.write(new_content)
    print("Successfully patched core/templates/core/voter_advanced_search.html")
else:
    print("Could not find the code block to patch in core/templates/core/voter_advanced_search.html")
