import paramiko
import os
import time

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/recheck_clients_v2.php")
        remote_path = f"{REMOTE_BASE}/scripts/recheck_clients_v2.php"
        tmp_remote = f"/tmp/recheck_v2_{os.getpid()}.php"
        
        print("📤 Upload script v2...")
        sftp.put(local_path, tmp_remote)
        ssh.exec_command(f"sudo mv {tmp_remote} {remote_path}")
        ssh.exec_command(f"sudo chown www-data:www-data {remote_path}")
        ssh.exec_command(f"sudo chmod 755 {remote_path}")
        
        sftp.close()
        
        print("\n🚀 Exécution de la re-vérification (V2)...")
        # Run in foreground to see output
        stdin, stdout, stderr = ssh.exec_command(f"cd {REMOTE_BASE} && php scripts/recheck_clients_v2.php")
        
        # Stream output
        while not stdout.channel.exit_status_ready():
            if stdout.channel.recv_ready():
                print(stdout.channel.recv(1024).decode(), end='')
            if stderr.channel.recv_ready():
                print(stderr.channel.recv(1024).decode(), end='')
            time.sleep(0.1)

        print(stdout.read().decode(), end='')
        print(stderr.read().decode(), end='')
        
        ssh.close()
        
    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    main()
