import sys

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

# 1. Find the line where deleteAction is declared
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)

# Insert flag action declaration right after it
flag_decl = '    QAction *flagAction = m_toolBar->addAction(\"🚩 Flag\");\n'
lines = lines[:decl_line+1] + [flag_decl] + lines[decl_line+1:]

# 2. Find the closing brace of the createToolBar function
brace_line = None
brace_count = 0
in_function = False
for i, line in enumerate(lines):
    if i < decl_line:
        continue
    if 'void MainMainWindow::createToolBar() {' in line:
        in_function = True
        continue
    if not in_function:
        continue
    # Count braces
    for ch in line:
        if ch == '{':
            brace_count += 1
        elif ch == '}':
            brace_count -= 1
            if brace_count == 0:
                brace_line = i
                break
    if brace_line is not None:
        break
if brace_line is None:
    print('Could not find closing brace of createToolBar')
    sys.exit(1)

# 3. Insert flag connection just before the closing brace
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(); // optional, to update icon if any
            } else {
                statusBar()->showMessage(tr("Failed to update flag"), 2000);
            }
        } else {
            statusBar()->showMessage(tr("Email not found"), 2000);
        }
    });\n'''
lines = lines[:brace_line] + [flag_conn] + lines[brace_line:]

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

print('Flag action added')
