import sys

filename = '/mnt/c/Users/javie/wino-mail-dtkqt/src/ui/mainmainwindow.cpp'
with open(filename, 'r') as f:
    lines = f.readlines()

# Find start line
start = None
for i, line in enumerate(lines):
    if line.strip().startswith('connect(deleteAction, &QAction::triggered'):
        start = i
        break
if start is None:
    print('Could not find deleteAction connect')
    sys.exit(1)

# Find end line: look for a line that contains '});' after start, assuming it's the end of the lambda
end = None
for i in range(start, len(lines)):
    if '});' in lines[i]:
        end = i
        break
if end is None:
    print('Could not find end of lambda')
    sys.exit(1)

# Replacement lines
new_lines = [
    '    connect(deleteAction, &QAction::triggered, [this]() {\n',
    '        QModelIndexList indexes = m_mailListView->selectionModel()->selectedIndexes();\n',
    '        if (indexes.isEmpty()) {\n',
    '            statusBar()->showMessage(tr(\"No email selected\"), 2000);\n',
    '            return;\n',
    '        }\n',
    '        int row = indexes.first().row();\n',
    '        QModelIndex idx = m_emailModel->index(row, 0);\n',
    '        qint64 id = idx.data(EmailListModel::IdRole).toLongLong();\n',
    '        m_mailService->deleteMail(QString::number(id));  // deletes from DB\n',
    '        m_emailModel->refresh();\n',
    '        statusBar()->showMessage(tr(\"Email deleted\"), 2000);\n',
    '    });\n'
]

# Replace
lines = lines[:start] + new_lines + lines[end+1:]

with open(filename, 'w') as f:
    f.writelines(lines)

print('Replace done')
