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 of delete connect
start = None
for i, line in enumerate(lines):
    if 'connect(deleteAction, &QAction::triggered' in line:
        start = i
        break
if start is None:
    print('Could not find delete connect start')
    sys.exit(1)

# Find end of that connect (the matching '});' after start)
end = None
brace_count = 0
for i in range(start, len(lines)):
    line = lines[i]
    for ch in line:
        if ch == '{':
            brace_count += 1
        elif ch == '}':
            brace_count -= 1
            if brace_count == 0 and '});' in line:
                end = i
                break
    if end is not None:
        break
if end is None:
    print('Could not find end of delete connect')
    sys.exit(1)

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

# Replace lines[start:end+1] with new_delete
lines = lines[:start] + [new_delete] + lines[end+1:]

# Now add flag action declaration after deleteAction declaration
decl_line = None
for i, line in enumerate(lines):
    if 'QAction *deleteAction = m_toolBar->addAction(\"🗑 Delete\");' in line:
        decl_line = i
        break
if decl_line is None:
    print('Could not find deleteAction declaration')
    sys.exit(1)

flag_decl = '    QAction *flagAction = m_toolBar->addAction(\"🚩 Flag\");\n'
lines = lines[:decl_line+1] + [flag_decl] + lines[decl_line+1:]

# Find where to insert flag connection: after the delete connect we just placed
# Search for the '});' that ends the new delete connect (starting from start)
insert_point = None
for i in range(start, len(lines)):
    if '});' in lines[i]:
        insert_point = i + 1
        break
if insert_point is None:
    insert_point = len(lines)

flag_conn = '''    connect(flagAction, &QAction::triggered, [this]() {
        QModelIndexList indexes = m_mailListView->selectionModel()->selectedIndexes();
        if (indexes.isEmpty()) {
            statusBar()->showMessage(tr("No email selected"), 2000);
            return;
        }
        int row = indexes.first().row();
        QModelIndex idx = m_emailModel->index(row, 0);
        qint64 id = idx.data(EmailListModel::IdRole).toLongLong();
        // Toggle flagged state
        std::optional<MailItem> opt = MailItemDao::findById(id);
        if (opt) {
            MailItem item = *opt;
            item.setFlagged(!item.isFlagged());
            if (MailItemDao::update(item)) {
                statusBar()->showMessage(tr("Flag toggled"), 2000);
                m_emailModel->refresh();
            } else {
                statusBar()->showMessage(tr("Failed to update flag"), 2000);
            }
        } else {
            statusBar()->showMessage(tr("Email not found"), 2000);
        }
    });\n'''
lines = lines[:insert_point] + [flag_conn] + lines[insert_point:]

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

print('Delete and flag actions updated')
