import React, { useState } from 'react'; import { motion } from 'motion/react'; import { getEnvStatus, testSupabaseConnection, testFirebaseConnection } from '../utils/envValidator'; import { encryptWithWebCrypto, decryptWithWebCrypto } from '../utils/encryption'; import { proxyFetch } from '../utils/apiProxy'; import { Activity, ShieldCheck, Database, Key, CheckCircle, XCircle, AlertTriangle, RefreshCw, Download, Play, Lock, BrainCircuit, Terminal, Sparkles, HelpCircle } from 'lucide-react'; interface TestResult { name: string; category: 'database' | 'security' | 'intelligence'; status: 'SUCCESS' | 'ERROR' | 'PENDING'; message: string; latency?: number; } export default function ConnectionTest({ lang = 'ar' }: { lang?: 'ar' | 'en' }) { const [runningAll, setRunningAll] = useState(false); const [envStatus, setEnvStatus] = useState(() => getEnvStatus()); const [tests, setTests] = useState>({ supabase: { name: 'Supabase Database', category: 'database', status: 'PENDING', message: lang === 'ar' ? 'بانتظار إجراء التحقق...' : 'Awaiting manual trigger...' }, firebase: { name: 'Firebase Firestore', category: 'database', status: 'PENDING', message: lang === 'ar' ? 'بانتظار إجراء التحقق...' : 'Awaiting manual trigger...' }, vault: { name: 'Secure Vault Encrypt', category: 'security', status: 'PENDING', message: lang === 'ar' ? 'بانتظار إجراء التحقق...' : 'Awaiting manual trigger...' }, gemini: { name: 'Google Gemini API', category: 'intelligence', status: 'PENDING', message: lang === 'ar' ? 'بانتظار إجراء التحقق...' : 'Awaiting manual trigger...' }, groq: { name: 'Groq Cloud LLM API', category: 'intelligence', status: 'PENDING', message: lang === 'ar' ? 'بانتظار إجراء التحقق...' : 'Awaiting manual trigger...' } }); const [lastTested, setLastTested] = useState(null); const refreshEnvStatus = () => { setEnvStatus(getEnvStatus()); }; const getEnvValue = (name: string): string => { const altName = name.replace('VITE_', ''); return (window as any).__ENV?.[name] || (window as any).__ENV?.[altName] || (window as any).env?.[name] || (window as any).env?.[altName] || (import.meta as any).env?.[name] || (import.meta as any).env?.[altName] || ''; }; const runSupabaseTest = async (): Promise => { setTests(prev => ({ ...prev, supabase: { ...prev.supabase, status: 'PENDING', message: lang === 'ar' ? 'جاري الاتصال والتحقق من الاستجابة...' : 'Pinging database endpoint...' } })); const res = await testSupabaseConnection(); const result: TestResult = { name: 'Supabase Database', category: 'database', status: res.status === 'SUCCESS' ? 'SUCCESS' : 'ERROR', message: res.message, latency: res.latencyMs }; setTests(prev => ({ ...prev, supabase: result })); return result; }; const runFirebaseTest = async (): Promise => { setTests(prev => ({ ...prev, firebase: { ...prev.firebase, status: 'PENDING', message: lang === 'ar' ? 'جاري طلب استعلام خادم Firestore...' : 'Pinging Firebase endpoint...' } })); const res = await testFirebaseConnection(); const result: TestResult = { name: 'Firebase Firestore', category: 'database', status: res.status === 'SUCCESS' ? 'SUCCESS' : 'ERROR', message: res.message, latency: res.latencyMs }; setTests(prev => ({ ...prev, firebase: result })); return result; }; const runVaultTest = async (): Promise => { setTests(prev => ({ ...prev, vault: { ...prev.vault, status: 'PENDING', message: lang === 'ar' ? 'جاري توليد مفتاح AES-GCM 256...' : 'Generating AES-GCM 256 crypt...' } })); const start = Date.now(); try { const originalText = "Eissa-Master-Sentry-Verification-2026"; const dummyPass = "Eissa2026"; // 1. Test Encryption const encrypted = await encryptWithWebCrypto(originalText, dummyPass); if (!encrypted || !encrypted.includes(':')) { throw new Error('فشل تشفير مفاتيح الخزنة.'); } // 2. Test Decryption const decrypted = await decryptWithWebCrypto(encrypted, dummyPass); if (decrypted !== originalText) { throw new Error('فشل فك التشفير: البيانات الناتجة مشوهة.'); } const result: TestResult = { name: 'Secure Vault Encrypt', category: 'security', status: 'SUCCESS', message: lang === 'ar' ? 'تشفير الخزنة يعمل بشكل ممتاز مع معيار AES-GCM 256.' : 'Vault dynamic cryptography fully operational (AES-GCM 256).', latency: Date.now() - start }; setTests(prev => ({ ...prev, vault: result })); return result; } catch (err: any) { const result: TestResult = { name: 'Secure Vault Encrypt', category: 'security', status: 'ERROR', message: lang === 'ar' ? `فشل فحص برمجية الخزنة: ${err.message || String(err)}` : `Vault cryptography error: ${err.message || String(err)}`, latency: Date.now() - start }; setTests(prev => ({ ...prev, vault: result })); return result; } }; const runGeminiTest = async (): Promise => { setTests(prev => ({ ...prev, gemini: { ...prev.gemini, status: 'PENDING', message: lang === 'ar' ? 'جاري فحص ترخيص محرك Gemini...' : 'Pinging Google Gemini API...' } })); const start = Date.now(); const token = getEnvValue('VITE_GEMINI_API_KEY'); if (!token) { const result: TestResult = { name: 'Google Gemini API', category: 'intelligence', status: 'ERROR', message: lang === 'ar' ? 'مفتاح Gemini مفقود! يرجى إعداده كمتغير بيئي.' : 'Gemini key is missing in active workspace variables.' }; setTests(prev => ({ ...prev, gemini: result })); return result; } try { // Small real call to gather metadata (highly safe & CORS proxy resolved) const url = `https://generativelanguage.googleapis.com/v1beta/models?key=${token}`; const res = await proxyFetch(url); const latency = Date.now() - start; if (res.status === 200) { const result: TestResult = { name: 'Google Gemini API', category: 'intelligence', status: 'SUCCESS', message: lang === 'ar' ? 'تم مصادقة مفتاح Gemini بنجاح. القنوات ذكية ومفتوحة!' : 'Gemini validation resolved with code 200. Models online.', latency }; setTests(prev => ({ ...prev, gemini: result })); return result; } else { const result: TestResult = { name: 'Google Gemini API', category: 'intelligence', status: 'ERROR', message: lang === 'ar' ? `رفضت Google المفتاح برمز (${res.status}).` : `Google gateway rejected token (HTTP status ${res.status}).`, latency }; setTests(prev => ({ ...prev, gemini: result })); return result; } } catch (err: any) { const result: TestResult = { name: 'Google Gemini API', category: 'intelligence', status: 'ERROR', message: lang === 'ar' ? `فشل الاتصال: ${err.message || 'خطأ في جدار الحماية'}` : `Fetch error: ${err.message || 'CORS or offline'}`, latency: Date.now() - start }; setTests(prev => ({ ...prev, gemini: result })); return result; } }; const runGroqTest = async (): Promise => { setTests(prev => ({ ...prev, groq: { ...prev.groq, status: 'PENDING', message: lang === 'ar' ? 'جاري فحص ترخيص خادم Groq السحابي...' : 'Pinging Groq Cloud API...' } })); const start = Date.now(); const token = getEnvValue('VITE_GROQ_API_KEY'); if (!token) { const result: TestResult = { name: 'Groq Cloud LLM API', category: 'intelligence', status: 'ERROR', message: lang === 'ar' ? 'المفتاح لم يتم تعيينه. يرجى إدخال VITE_GROQ_API_KEY.' : 'Groq API Key is not set.' }; setTests(prev => ({ ...prev, groq: result })); return result; } try { // Probe Models API (lightweight endpoint check) const res = await proxyFetch('https://api.groq.com/openai/v1/models', { headers: { 'Authorization': `Bearer ${token}` } }); const latency = Date.now() - start; if (res.status === 200) { const result: TestResult = { name: 'Groq Cloud LLM API', category: 'intelligence', status: 'SUCCESS', message: lang === 'ar' ? 'الاتصال بـ Groq نشط ومصرح للاستدعاء بنجاح.' : 'Groq gateway authentication successful. High-speed LLM online.', latency }; setTests(prev => ({ ...prev, groq: result })); return result; } else { const result: TestResult = { name: 'Groq Cloud LLM API', category: 'intelligence', status: 'ERROR', message: lang === 'ar' ? `مفاتيح غير مصرحة في خادم Groq (${res.status}).` : `Groq rejected the authorization (HTTP status ${res.status}).`, latency }; setTests(prev => ({ ...prev, groq: result })); return result; } } catch (err: any) { const result: TestResult = { name: 'Groq Cloud LLM API', category: 'intelligence', status: 'ERROR', message: lang === 'ar' ? `فشل المصافحة: CORS أو خادم غير متصل بالإنترنت.` : `Handshake exception: CORS restriction or destination model server is offline.`, latency: Date.now() - start }; setTests(prev => ({ ...prev, groq: result })); return result; } }; const runAllDiagnostics = async () => { setRunningAll(true); refreshEnvStatus(); await runSupabaseTest(); await runFirebaseTest(); await runVaultTest(); await runGeminiTest(); await runGroqTest(); setLastTested(new Date().toLocaleTimeString()); setRunningAll(false); }; const exportJSONResults = () => { const dataStr = "data:text/json;charset=utf-8," + encodeURIComponent( JSON.stringify({ timestamp: new Date().toISOString(), environmentVariables: envStatus, connectionTests: tests }, null, 2) ); const downloadAnchor = document.createElement('a'); downloadAnchor.setAttribute("href", dataStr); downloadAnchor.setAttribute("download", `Sentry_Diagnostic_Report_${Date.now()}.json`); document.body.appendChild(downloadAnchor); downloadAnchor.click(); downloadAnchor.remove(); }; return (
{/* Test Controls Banner */}
{/* Colorful Gradient Light effect */}

{lang === 'ar' ? 'لوحة الاختبارات والتشخيص الذاتي' : 'Sentry AI Active Diagnostic Console'}

{lang === 'ar' ? 'قم بمراقبة وفحص اتصالات قواعد البيانات السحابية، وسلامة تراخيص ذكاء قوين الاصطناعي، ومزامنة المتغيرات البيئية من مكان واحد.' : 'Execute end-to-end cloud database ping tests, verify cryptographic master key vaults, and inspect active Gemini and Groq API handshakes.'}

{lastTested && (

{lang === 'ar' ? `آخر فحص نشط: ${lastTested}` : `Last telemetry probe: ${lastTested}`}

)}
{/* Main Grid: Variables list & Connection status */}
{/* Box 1: Env vars audit (Masqued panel) */}

{lang === 'ar' ? 'التحقق من متغيرات البيئة' : 'Active Keys & Environment Variables'}

{lang === 'ar' ? 'تُسحب هذه المفاتيح تلقائياً ومباشرة من إعدادات Hugging Face Secrets لضمان حماية خادم العميل القصوى وعدم كشف الرموز للمتصفح.' : 'Environment variables are loaded securely from your hosting Secrets context. Values are masked to protect authorization endpoints.'}

{envStatus.map((env, idx) => (
{env.keyName} {env.isOptional && ( OPTIONAL )}
{env.maskedValue}
{env.isLoaded ? ( {lang === 'ar' ? 'جاهز' : 'Loaded'} ) : ( {lang === 'ar' ? 'غير متوفر' : 'Missing'} )}
))}
{/* Box 2: Test Suites and Latency logs */}

{lang === 'ar' ? 'فحوصات الاتصال السحابية النشطة' : 'Active Connection Guard Tests'}

TELEMETRY_SUITE
{/* Supabase Box */}

{lang === 'ar' ? 'قاعدة بيانات Supabase الموحدة' : 'Supabase Multi-Tenant Engine'} {tests.supabase.latency !== undefined && ( {tests.supabase.latency}ms )}

{tests.supabase.message}

{/* Firebase Box */}

{lang === 'ar' ? 'جسر البيانات السحابي Firebase Auth' : 'Firebase Firestore & OAuth'} {tests.firebase.latency !== undefined && ( {tests.firebase.latency}ms )}

{tests.firebase.message}

{/* Vault Box */}

{lang === 'ar' ? 'خزنة التشفير AES-GCM 256' : 'AES Cryptographic Web Crypto Vault'} {tests.vault.latency !== undefined && ( {tests.vault.latency}ms )}

{tests.vault.message}

{/* Gemini Box */}

{lang === 'ar' ? 'محرك Google Gemini وقسائم الذكاء' : 'Google Gemini AI Endpoint'} {tests.gemini.latency !== undefined && ( {tests.gemini.latency}ms )}

{tests.gemini.message}

{/* Groq Box */}

{lang === 'ar' ? 'بوابة Groq Cloud فائقة السرعة' : 'Groq Cloud High-Speed Gateway'} {tests.groq.latency !== undefined && ( {tests.groq.latency}ms )}

{tests.groq.message}

); } function StatusMarker({ status, lang }: { status: 'SUCCESS' | 'ERROR' | 'PENDING', lang: 'ar' | 'en' }) { if (status === 'SUCCESS') { return ( {lang === 'ar' ? 'مستقر' : 'SUCCESS'} ); } if (status === 'ERROR') { return ( {lang === 'ar' ? 'فشل' : 'FAILED'} ); } return ( {lang === 'ar' ? 'بانتظار الفحص' : 'PENDING'} ); }