import sys

filename = 'mainmainwindow.cpp'
with open(filename, 'r') as f:
    lines = f.readlines()

# Find the line after the mailFetchError connect (look for the closing brace and semicolon of that connect)
# We'll look for the pattern: '});' that ends the mailFetchError lambda.
insert_idx = None
for i, line in enumerate(lines):
    if 'connect(m_mailService, &MailService::mailFetchError' in line:
        # Find the closing brace of this call (could be same line or later)
        # We'll just look for the next line that contains '});' after this line.
        for j in range(i, len(lines)):
            if '});' in lines[j]:
                insert_idx = j + 1  # insert after this line
                break
        break

if insert_idx is None:
    print("Could not find insert point")
    sys.exit(1)

# The insertion block
insert_lines = [
    '    connect(m_mailService, &MailService::mailSendFailed, this, [this](const QString &mailItemId, const QString &error) {\n',
    '        qWarning() << \"[MailSendFailed]\" << error;\n',
    '        statusBar()->showMessage(tr(\"Error sending mail: %1\").arg(error), 5000);\n',
    '    });\n'
]

# Insert
lines = lines[:insert_idx] + insert_lines + lines[insert_idx:]

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

print(f"Inserted mailSendFailed connection at line {insert_idx+1}")
