import paramiko
from datetime import datetime

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)
        
        print("🔍 Vérification de la synchronisation...")
        print("=" * 60)
        
        # Check last scan log
        print("\n📋 Dernière exécution du scanner:")
        stdin, stdout, stderr = ssh.exec_command(f"tail -n 20 {REMOTE_BASE}/data/logs/scan.log 2>/dev/null || echo 'Fichier scan.log non trouvé'")
        log = stdout.read().decode()
        
        if log and 'non trouvé' not in log:
            lines = log.strip().split('\n')
            print(f"   Dernières lignes (sur {len(lines)}):")
            for line in lines[-5:]:
                print(f"   {line}")
        else:
            print("   ⚠️ Aucun log de scan trouvé")
        
        # Check queue.csv modification time
        print("\n📅 Dernière modification de queue.csv:")
        stdin, stdout, stderr = ssh.exec_command(f"stat -c '%y' {REMOTE_BASE}/data/queue.csv")
        mod_time = stdout.read().decode().strip()
        print(f"   {mod_time}")
        
        # Check cron status
        print("\n⏰ Vérification du CRON job:")
        stdin, stdout, stderr = ssh.exec_command("crontab -l | grep scan.php")
        cron = stdout.read().decode().strip()
        if cron:
            print(f"   ✅ CRON actif: {cron}")
        else:
            print("   ❌ CRON non trouvé!")
        
        # Force scan
        print("\n🔄 Lancement d'un scan manuel...")
        stdin, stdout, stderr = ssh.exec_command(f"cd {REMOTE_BASE} && php scripts/scan.php")
        scan_output = stdout.read().decode()
        scan_error = stderr.read().decode()
        
        if scan_output:
            print("   Résultat:")
            print(scan_output[:500])  # First 500 chars
        
        if scan_error:
            print("   Erreurs/Warnings:")
            # Filter out common warnings
            errors = [e for e in scan_error.split('\n') if e and 'Undefined array key' not in e]
            for err in errors[:5]:
                print(f"   {err}")
        
        # Check queue.csv again
        print("\n📊 Nombre de messages après scan:")
        stdin, stdout, stderr = ssh.exec_command(f"wc -l {REMOTE_BASE}/data/queue.csv")
        count = stdout.read().decode().strip()
        print(f"   {count}")
        
        ssh.close()
        print("\n✅ Vérification terminée!")
        
    except Exception as e:
        print(f"❌ Error: {e}")
        import traceback
        traceback.print_exc()

if __name__ == "__main__":
    main()
