import re

with open("static/js/bottom-bar.js", "r") as f:
    text = f.read()

# Replace the static select with a dynamic fetch container
events_html = """
            const replyBox = document.createElement('div');
            replyBox.className = 'mt-2 border-top pt-2 border-primary-subtle';
            replyBox.innerHTML = `
                <div class="input-group input-group-sm mb-1">
                    <span class="input-group-text bg-light text-muted border-0"><i class="bi bi-person"></i></span>
                    <select id="chatRecipient" class="form-select border-0 bg-light">
                        <option value="all">Indlæser brugere...</option>
                    </select>
                </div>
                <div class="input-group">
                    <input type="text" id="chatInputQuick" class="form-control form-control-sm" placeholder="Skriv en besked...">
                    <button class="btn btn-outline-primary btn-sm" id="btnSendMsg"><i class="bi bi-send"></i></button>
                </div>
            `;
            
            chatContainer.appendChild(ul);
            chatContainer.appendChild(replyBox);
            innerContent.appendChild(chatContainer);
            
            // Fetch users dynamically
            fetch('/api/v1/users?is_active=true', { credentials: 'include' })
            .then(r => r.json())
            .then(users => {
                const sel = document.getElementById('chatRecipient');
                if (sel) {
                    sel.innerHTML = '<option value="all">Alle på vagt</option><option value="system">System (Bot)</option>';
                    users.forEach(u => {
                        sel.innerHTML += `<option value="${u.id}">${u.name || u.email}</option>`;
                    });
                }
            })
            .catch(e => console.error("Error fetching users for chat:", e));
        } else {
            innerContent.appendChild(ul);
        }
"""

# Find the block we inserted earlier and replace it
pattern = r"            const replyBox = document\.createElement\('div'\);\n            replyBox\.className = 'mt-2 border-top pt-2 border-primary-subtle';\n            replyBox\.innerHTML = `[\s\S]*?innerContent\.appendChild\(chatContainer\);\n        \} else \{\n            innerContent\.appendChild\(ul\);\n        \}"
# print(re.search(pattern, text))
text = re.sub(pattern, events_html, text)

# Then bump the cache version
with open("static/js/bottom-bar.js", "w") as f:
    f.write(text)

with open("app/shared/frontend/base.html", "r") as f:
    bt = f.read()
    bt = re.sub(r'bottom-bar\.js\?v=\d+\.\d+', 'bottom-bar.js?v=2.00', bt)
    with open("app/shared/frontend/base.html", "w") as f2:
        f2.write(bt)
