import paramiko
import sys
import os

HOST = "135.125.102.180"
USER = "ubuntu"
PASS = "BotPascal2026!"
SCRIPT_NAME = "test_scan_live.php"
LOCAL_TMP = "test_scan_live.php"
REMOTE_PATH = "/var/www/html/repondeur_mail_grok/scripts/test_scan_live.php"

PHP_CODE = """<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../core/ImapClient.php';
require_once __DIR__ . '/../core/Logger.php';

echo "--- START TEST ---" . PHP_EOL;
try {
    $imap = new ImapClient();
    echo "Connected." . PHP_EOL;
    
    echo "Fetching 5 Unread..." . PHP_EOL;
    $mails = $imap->fetchUnread(5);
    
    echo "Count: " . count($mails) . PHP_EOL;
    foreach ($mails as $m) {
        echo " - UID: " . $m['uid'] . " | From: " . $m['from'] . " | Name: " . ($m['from_name'] ?? 'N/A') . PHP_EOL;
    }
    
    $imap->close();
    echo "Closed." . PHP_EOL;
} catch (Exception $e) {
    echo "ERROR: " . $e->getMessage() . PHP_EOL;
}
echo "--- END TEST ---" . PHP_EOL;
"""

def main():
    try:
        # Create local file first
        with open(LOCAL_TMP, "w") as f:
            f.write(PHP_CODE)

        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username=USER, password=PASS)
        
        # SFTP Upload
        sftp = ssh.open_sftp()
        tmp_remote = "/tmp/" + SCRIPT_NAME
        print(f"Uploading {LOCAL_TMP} -> {tmp_remote}")
        sftp.put(os.path.abspath(LOCAL_TMP), tmp_remote)
        sftp.close()
        
        # Move and run
        ssh.exec_command(f"sudo mv {tmp_remote} {REMOTE_PATH}")
        
        print("Running test...")
        stdin, stdout, stderr = ssh.exec_command(f"php {REMOTE_PATH}")
        print(stdout.read().decode())
        err = stderr.read().decode()
        if err:
            print(f"STDERR: {err}")
            
        ssh.close()
        # Cleanup local
        os.remove(LOCAL_TMP)
    except Exception as e:
        print(f"Error: {e}")

if __name__ == "__main__":
    main()
