#!/usr/bin/env python3
import paramiko

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

ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(HOST, username=USER, password=PASS)

print("🔍 Ré-analyse des clients et sites pour les messages en attente...")

# Script PHP corrigé pour utiliser searchClient() à la place de findClientAcrossShops()
php_script = """
<?php
require_once '/var/www/html/repondeur_mail_grok/core/CsvHandler.php';
require_once '/var/www/html/repondeur_mail_grok/core/PrestaShop.php';
require_once '/var/www/html/repondeur_mail_grok/config/config.php';

$queue = CsvHandler::read(FILE_QUEUE);
$presta = new PrestaShop();
$updated = 0;

foreach ($queue as &$item) {
    if (empty($item['shop_id']) && !empty($item['email'])) {
        echo "Recherche pour " . $item['email'] . "... ";
        // CORRECTED METHOD NAME
        $clientInfo = $presta->searchClient($item['email']);
        if ($clientInfo) {
            $item['shop_id'] = $clientInfo['shop_id'];
            $item['client_id'] = $clientInfo['customer']['id'];
            $item['sender_name'] = $clientInfo['customer']['firstname'] . ' ' . $clientInfo['customer']['lastname'];
            
            // Get last order
            $orderInfo = $presta->getLastOrderInfo($item['shop_id'], $item['client_id']);
            if ($orderInfo) {
                $item['last_order_date'] = $orderInfo['date'];
                $item['last_order_ref'] = $orderInfo['reference'];
            }
            
            echo "TROUVÉ: Shop " . $item['shop_id'] . "\\n";
            $updated++;
        } else {
            echo "Non trouvé.\\n";
        }
    }
}

if ($updated > 0) {
    CsvHandler::overwrite(FILE_QUEUE, $queue);
    echo "\\n✅ $updated messages mis à jour avec succès.\\n";
} else {
    echo "\\nℹ️ Aucun nouveau client identifié.\\n";
}
?>
"""

stdin, stdout, stderr = ssh.exec_command("cat > /tmp/recheck_fix.php << 'EOF'\n" + php_script + "\nEOF")
stdin, stdout, stderr = ssh.exec_command("php /tmp/recheck_fix.php")
print(stdout.read().decode())
print(stderr.read().decode())

ssh.close()
