import sqlite3
from datetime import datetime, timezone

def run_migration():
    conn = sqlite3.connect('instance/ngo.db')
    c = conn.cursor()
    c.execute('PRAGMA table_info(contact_messages)')
    existing_cols = {col[1] for col in c.fetchall()}
    print('Existing cols in contact_messages:', existing_cols)

    cols_to_add = [
        ('reference_no', 'VARCHAR(50)'),
        ('admin_reply', 'TEXT'),
        ('follow_up_notes', 'TEXT'),
        ('replied_at', 'DATETIME'),
        ('replied_by_id', 'INTEGER'),
        ('email_sent', 'BOOLEAN DEFAULT 0'),
        ('email_sent_at', 'DATETIME'),
        ('updated_at', 'DATETIME')
    ]

    for col_name, col_type in cols_to_add:
        if col_name not in existing_cols:
            print(f'Adding column: {col_name}')
            c.execute(f'ALTER TABLE contact_messages ADD COLUMN {col_name} {col_type}')

    # Backfill reference_no for rows that have NULL or empty reference_no
    c.execute('SELECT id FROM contact_messages WHERE reference_no IS NULL OR reference_no = ""')
    rows = c.fetchall()
    for idx, (row_id,) in enumerate(rows, start=1):
        ref_no = f'ENQ-2026-{idx:04d}'
        c.execute('UPDATE contact_messages SET reference_no = ? WHERE id = ?', (ref_no, row_id))
        print(f'Backfilled contact_message {row_id} with {ref_no}')

    conn.commit()
    c.execute('PRAGMA table_info(contact_messages)')
    print('Updated cols in contact_messages:', [col[1] for col in c.fetchall()])
    conn.close()

if __name__ == '__main__':
    run_migration()
