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/recheck_clients.php")
        remote_path = f"{REMOTE_BASE}/scripts/recheck_clients.php"
        tmp_remote = f"/tmp/recheck_{os.getpid()}.php"
        
        print("📤 Upload script...")
        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 vérification clients...")
        # Increase timeout as this might take a while with API calls
        stdin, stdout, stderr = ssh.exec_command(f"cd {REMOTE_BASE} && php scripts/recheck_clients.php")
        
        output = stdout.read().decode()
        error = stderr.read().decode()
        
        if output:
            print(output)
        if error:
            print(f"⚠️ ERRORS:\n{error}")
            
        print("\n✅ Terminé!")
        
        ssh.close()
        
    except Exception as e:
        print(f"❌ Error: {e}")

if __name__ == "__main__":
    main()
