import re

with open('index.php', 'r', encoding='utf-8') as f:
    content = f.read()

# Replace the handler
old_handler = """    var instanceModal = document.getElementById('instanceModal');
    instanceModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        if (!button) return;

        var personId = button.dataset.personId || '';
        var processId = button.dataset.processId || '';
        var processCode = button.dataset.processCode || '';
        var subjectType = button.dataset.subjectType || 'person';
        var subjectId = button.dataset.subjectId || personId;
        var cycleKey = button.dataset.cycleKey || '';

        instanceModal.dataset.lastPersonId = personId;
        instanceModal.dataset.lastProcessId = processId;
        instanceModal.dataset.lastProcessCode = processCode;
        instanceModal.dataset.lastSubjectType = subjectType;
        instanceModal.dataset.lastSubjectId = subjectId;
        instanceModal.dataset.lastCycleKey = cycleKey;

        var modalBody = instanceModal.querySelector('.modal-body');
        modalBody.innerHTML = '<div class="text-center mt-4"><div class="spinner-border text-primary" role="status"></div><p class="mt-2">Ladowanie...</p></div>';

        var url = '_get_instance_details.php?subject_type=' + encodeURIComponent(subjectType) + '&subject_id=' + encodeURIComponent(subjectId);
        if (personId) url += '&person_id=' + encodeURIComponent(personId);
        if (processId) url += '&process_id=' + encodeURIComponent(processId);
        if (processCode) url += '&process_code=' + encodeURIComponent(processCode);
        if (cycleKey) url += '&cycle_key=' + encodeURIComponent(cycleKey);

        fetch(url)
            .then(function(response) {
                if (!response.ok) {
                    return response.text().then(function(text) {
                        var errStr = 'HTTP ' + response.status + ': ';
                        var corrId = '';
                        try {
                            var data = JSON.parse(text);
                            errStr += (data.error && data.error.message) ? data.error.message : (data.error || text);
                            if (data.correlation_id) corrId = data.correlation_id;
                        } catch (e) {
                            errStr += text.substring(0, 100);
                        }
                        throw new Error(errStr + (corrId ? ' (ID: ' + corrId + ')' : ''));
                    });
                }
                return response.text();
            })
            .then(function(html) {
                modalBody.innerHTML = html;
                var returnedTitle = modalBody.querySelector('#instance-modal-title');
                if (returnedTitle) {
                    var modalTitleElem = instanceModal.querySelector('.modal-title');
                    if (modalTitleElem) {
                        modalTitleElem.innerHTML = returnedTitle.innerHTML;
                        returnedTitle.remove();
                    }
                }
            })
            .catch(function(err) {
                console.error('Fetch error:', err);
                modalBody.innerHTML = '<div class="alert alert-danger m-3"><strong>Błąd ładowania:</strong><br>' + err.message + '</div>';
            });
    });"""

new_handler = """    var instanceModal = document.getElementById('instanceModal');
    instanceModal.addEventListener('show.bs.modal', function (event) {
        var button = event.relatedTarget;
        if (!button) return;

        var subjectType = button.dataset.subjectType || 'person';
        var subjectId = button.dataset.subjectId || button.dataset.personId || '';
        var personId = button.dataset.personId || '';
        var processId = button.dataset.processId || '';
        var processCode = button.dataset.processCode || '';
        var cycleKey = button.dataset.cycleKey || '';

        instanceModal.dataset.lastSubjectType = subjectType;
        instanceModal.dataset.lastSubjectId = subjectId;
        instanceModal.dataset.lastPersonId = personId;
        instanceModal.dataset.lastProcessId = processId;
        instanceModal.dataset.lastProcessCode = processCode;
        instanceModal.dataset.lastCycleKey = cycleKey;

        var modalTitle = instanceModal.querySelector('.modal-title');
        var modalBody = instanceModal.querySelector('.modal-body');

        modalTitle.textContent = 'Ładowanie...';
        modalBody.innerHTML = '<div class="text-center mt-4"><div class="spinner-border text-primary" role="status"></div><p class="mt-2">Ladowanie...</p></div>';

        if (!subjectId) {
            modalTitle.textContent = 'Błąd parametru';
            modalBody.innerHTML = '<div class="alert alert-danger m-3">Brak wymaganego identyfikatora (subject_id). Nie można załadować procesu.</div>';
            return;
        }

        if (!processId && !processCode) {
            modalTitle.textContent = 'Błąd parametru';
            modalBody.innerHTML = '<div class="alert alert-danger m-3">Brak identyfikatora procesu (process_id lub process_code). Nie można załadować procesu.</div>';
            return;
        }

        var url = '_get_instance_details.php?subject_type=' + encodeURIComponent(subjectType) + '&subject_id=' + encodeURIComponent(subjectId);
        if (personId) url += '&person_id=' + encodeURIComponent(personId);
        if (processId) url += '&process_id=' + encodeURIComponent(processId);
        if (processCode) url += '&process_code=' + encodeURIComponent(processCode);
        if (cycleKey) url += '&cycle_key=' + encodeURIComponent(cycleKey);

        fetch(url)
            .then(function(response) {
                if (!response.ok) {
                    return response.text().then(function(text) {
                        var errStr = 'HTTP ' + response.status + ': ';
                        var corrId = '';
                        try {
                            var data = JSON.parse(text);
                            errStr += (data.error && data.error.message) ? data.error.message : (data.error || text);
                            if (data.correlation_id) corrId = data.correlation_id;
                        } catch (e) {
                            errStr += text.substring(0, 100);
                        }
                        throw new Error(errStr + (corrId ? ' (ID: ' + corrId + ')' : ''));
                    });
                }
                return response.text();
            })
            .then(function(html) {
                modalBody.innerHTML = html;
                var returnedTitle = modalBody.querySelector('#instance-modal-title');
                if (returnedTitle) {
                    modalTitle.innerHTML = returnedTitle.innerHTML;
                    returnedTitle.remove();
                } else {
                    modalTitle.textContent = 'Szczegóły Procesu';
                }
            })
            .catch(function(err) {
                console.error('Fetch error:', err);
                modalTitle.textContent = 'Błąd';
                modalBody.innerHTML = '<div class="alert alert-danger m-3"><strong>Błąd ładowania:</strong><br>' + err.message + '</div>';
            });
    });"""

if old_handler in content:
    content = content.replace(old_handler, new_handler)
else:
    print("Could not find the old handler exactly as written. Applying regex replacement instead.")
    # More robust replacement
    start_str = "var instanceModal = document.getElementById('instanceModal');\n    instanceModal.addEventListener('show.bs.modal', function (event) {"
    start_idx = content.find(start_str)
    if start_idx != -1:
        end_idx = content.find("});", start_idx) + 3
        # Look for the next section to make sure we got the right block
        next_section = content.find("    // Bulk actions", end_idx)
        if next_section != -1 and next_section - end_idx < 100:
             content = content[:start_idx] + new_handler + content[end_idx:]
        else:
             print("Found start but next section is too far. Replacing block anyway.")
             content = content[:start_idx] + new_handler + content[end_idx:]


with open('index.php', 'w', encoding='utf-8') as f:
    f.write(content)
print("index.php patched (step 4)")
