import paramiko
import os

HOST = "135.125.102.180"
USER = "ubuntu"
PASS = "BotPascal2026!"
REMOTE_BASE = "/var/www/html/repondeur_mail_grok"

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()
        
        local_path = os.path.join(os.getcwd(), "scripts/sender.php")
        remote_path = f"{REMOTE_BASE}/scripts/sender.php"
        tmp_remote = f"/tmp/sender.php_{os.getpid()}"
        
        print(f"📤 Uploading corrected sender.php...")
        sftp.put(local_path, tmp_remote)
        
        print(f"📦 Moving to {remote_path}...")
        ssh.exec_command(f"sudo mv {tmp_remote} {remote_path}")
        
        print(f"🔐 Setting permissions...")
        ssh.exec_command(f"sudo chown www-data:www-data {remote_path}")
        ssh.exec_command(f"sudo chmod 755 {remote_path}")
        
        sftp.close()
        
        # Now run it
        print(f"\n🚀 Exécution du sender corrigé...")
        cmd = f"cd {REMOTE_BASE} && php scripts/sender.php"
        stdin, stdout, stderr = ssh.exec_command(cmd)
        
        output = stdout.read().decode()
        error = stderr.read().decode()
        
        if output:
            print("\n📤 OUTPUT:")
            print(output)
        
        if error:
            print("\n⚠️ ERRORS:")
            print(error)
        
        # Check archives
        print("\n✅ Vérification des archives...")
        stdin, stdout, stderr = ssh.exec_command(f"tail -n 3 {REMOTE_BASE}/data/archives.csv")
        archives = stdout.read().decode()
        if archives:
            print(archives)
        
        ssh.close()
        print("\n✅ Déploiement et test terminés!")
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()
