import paramiko

HOST = "135.125.102.180"
USER = "ubuntu"
PASS = "BotPascal2026!"

def main():
    try:
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(HOST, username=USER, password=PASS)
        
        php_code = """<?php
require_once '/var/www/html/repondeur_mail_grok/config/config.php';
require_once '/var/www/html/repondeur_mail_grok/core/CsvHandler.php';

$keywords = [];
if (file_exists(FILE_SPAM)) {
    $rows = array_map('str_getcsv', file(FILE_SPAM));
    array_shift($rows);
    foreach ($rows as $r) {
        if (!empty($r[0]))
            $keywords[] = strtolower(trim($r[0]));
    }
}

$queue = CsvHandler::read(FILE_QUEUE);
echo "QUEUE SIZE: " . count($queue) . "\\n";
if (!empty($queue)) {
    echo "--- FIRST ITEM DUMP ---\\n";
    print_r($queue[0]);
}

$matches = [];

foreach ($queue as $item) {
    $subject = strtolower($item['subject'] ?? '');
    $email = strtolower($item['email'] ?? '');
    $senderName = strtolower($item['sender_name'] ?? '');
    $body = strtolower($item['body'] ?? '');

    $matchedKw = null;
    foreach ($keywords as $kw) {
        if (
            strpos($subject, $kw) !== false ||
            strpos($email, $kw) !== false ||
            strpos($senderName, $kw) !== false ||
            strpos($body, $kw) !== false
        ) {
            $matchedKw = $kw;
            break;
        }
    }

    if ($matchedKw) {
        $matches[] = [
            'id' => $item['id'],
            'subject' => $item['subject'],
            'from' => $item['email'],
            'matched_keyword' => $matchedKw
        ];
    }
}

echo "TOTAL MATCHES: " . count($matches) . "\\n";
foreach (array_slice($matches, 0, 10) as $m) {
    echo "ID: {$m['id']} | KW: {$m['matched_keyword']} | From: {$m['from']}\\n";
}
?>"""
        
        # Write to tmp
        stdin, stdout, stderr = ssh.exec_command("cat > /tmp/simulate_api.php")
        stdin.write(php_code)
        stdin.channel.shutdown_write()
        
        print(stdout.read().decode())
        print(stderr.read().decode())

        # Run from tmp
        cmd = "php /tmp/simulate_api.php"
        stdin, stdout, stderr = ssh.exec_command(cmd)
        
        print(stdout.read().decode())
        print(stderr.read().decode())
        
        ssh.close()
    except Exception as e:
        print(e)

if __name__ == "__main__":
    main()
