import paramiko
import csv
import io
import sys

HOST = "135.125.102.180"
USER = "ubuntu"
PASS = "BotPascal2026!"
REMOTE_FILE = "/var/www/html/repondeur_mail_grok/data/queue.csv"

def main():
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username=USER, password=PASS)
        
        sftp = ssh.open_sftp()
        
        # Read remote file
        try:
            with sftp.open(REMOTE_FILE, 'r') as f:
                content = f.read().decode('utf-8')
        except IOError:
            print("File not found.")
            return

        # Parse CSV
        f_io = io.StringIO(content)
        reader = csv.reader(f_io)
        rows = list(reader)
        
        if not rows:
            print("Empty CSV.")
            return

        header = rows[0]
        if 'body' in header:
            print("Column 'body' already exists.")
            return

        print("Adding 'body' column...")
        header.append('body')
        
        # Update rows
        new_rows = [header]
        for row in rows[1:]:
            row.append('') # Empty body for existing
            new_rows.append(row)
            
        # Write back
        f_out = io.StringIO()
        writer = csv.writer(f_out)
        writer.writerows(new_rows)
        
        with sftp.open(REMOTE_FILE, 'w') as f:
            f.write(f_out.getvalue())
            
        print("Migration complete.")
        ssh.close()

    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()
