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)
        
        # 1. Kill any running recheck processes
        print("🛑 Arrêt des scans en cours...")
        ssh.exec_command("sudo pkill -f recheck_clients")
        time.sleep(1)
        
        # 2. Deploy quick fix
        sftp = ssh.open_sftp()
        local_path = os.path.join(os.getcwd(), "scripts/quick_fix_clients.php")
        remote_path = f"{REMOTE_BASE}/scripts/quick_fix_clients.php"
        tmp_remote = f"/tmp/quick_fix_{os.getpid()}.php"
        
        print("📤 Upload quick fix...")
        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}")
        
        # 3. Run quick fix
        print("🚀 Exécution du correctif immédiat...")
        stdin, stdout, stderr = ssh.exec_command(f"cd {REMOTE_BASE} && php scripts/quick_fix_clients.php")
        print(stdout.read().decode())
        
        sftp.close()
        ssh.close()
        
    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    main()
