<?php
/**
 * SUDANNA v23.4 — Flow Execution Test
 * Access: /test_flows.php?token=sudanna_test_2026
 * DELETE IMMEDIATELY AFTER TESTING
 */
if (($_GET['token'] ?? '') !== 'sudanna_test_2026') {
    http_response_code(403);
    die(json_encode(['error' => 'forbidden']));
}

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/engine/Gateway.php';
require_once __DIR__ . '/engine/AIClient.php';
AIClient::reset();

header('Content-Type: application/json; charset=utf-8');

$results = [];

// ── TEST 1: محتاج محامي ────────────────────────────────────────
$t1_start = microtime(true);
try {
    $r1 = Gateway::handle([
        'question' => 'محتاج محامي',
        'user'     => null,
        'ip'       => '127.0.0.1',
    ]);
    $results['test1_legal'] = [
        'input'   => 'محتاج محامي',
        'service' => $r1['service'] ?? 'NOT_SET',
        'source'  => $r1['source']  ?? 'NOT_SET',
        'has_flow'=> isset($r1['flow']),
        'has_answer'=> !empty($r1['answer']),
        'answer_preview'=> mb_substr($r1['answer'] ?? '', 0, 80),
        'latency_ms' => round((microtime(true)-$t1_start)*1000),
        'PASS' => ($r1['service'] ?? '') === 'legal' || ($r1['source'] ?? '') === 'ie',
    ];
} catch (Throwable $e) {
    $results['test1_legal'] = ['ERROR' => $e->getMessage(), 'PASS' => false];
}

// ── TEST 2: عايز مشروع ────────────────────────────────────────
$t2_start = microtime(true);
try {
    $r2 = Gateway::handle([
        'question' => 'عايز مشروع',
        'user'     => null,
        'ip'       => '127.0.0.2',
    ]);
    $results['test2_business'] = [
        'input'   => 'عايز مشروع',
        'service' => $r2['service'] ?? 'NOT_SET',
        'source'  => $r2['source']  ?? 'NOT_SET',
        'has_flow'=> isset($r2['flow']),
        'has_answer'=> !empty($r2['answer']),
        'answer_preview'=> mb_substr($r2['answer'] ?? '', 0, 80),
        'latency_ms' => round((microtime(true)-$t2_start)*1000),
        'PASS' => ($r2['service'] ?? '') === 'business' || ($r2['source'] ?? '') === 'ie',
    ];
} catch (Throwable $e) {
    $results['test2_business'] = ['ERROR' => $e->getMessage(), 'PASS' => false];
}

// ── TEST 3: ما سودانا؟ (platform/offline) ──────────────────────
$t3_start = microtime(true);
try {
    $r3 = Gateway::handle([
        'question' => 'ما سودانا؟',
        'user'     => null,
        'ip'       => '127.0.0.3',
    ]);
    $results['test3_platform'] = [
        'input'   => 'ما سودانا؟',
        'service' => $r3['service'] ?? 'NOT_SET',
        'source'  => $r3['source']  ?? 'NOT_SET',
        'has_answer'=> !empty($r3['answer']),
        'answer_preview'=> mb_substr($r3['answer'] ?? '', 0, 80),
        'latency_ms' => round((microtime(true)-$t3_start)*1000),
        'PASS' => !empty($r3['answer']),
    ];
} catch (Throwable $e) {
    $results['test3_platform'] = ['ERROR' => $e->getMessage(), 'PASS' => false];
}

// ── TEST 4: DB connectivity ─────────────────────────────────────
try {
    $tables = db()->query("SHOW TABLES")->fetchAll(PDO::FETCH_COLUMN);
    $providers = (int)db()->query("SELECT COUNT(*) FROM users WHERE provider_verified=1")->fetchColumn();
    $tasks_count = (int)db()->query("SELECT COUNT(*) FROM tasks")->fetchColumn();
    $flows_count = (int)db()->query("SELECT COUNT(*) FROM flow_sessions")->fetchColumn();
    $results['test4_db'] = [
        'tables_count' => count($tables),
        'verified_providers' => $providers,
        'tasks_in_queue' => $tasks_count,
        'flow_sessions' => $flows_count,
        'PASS' => count($tables) >= 70,
    ];
} catch (Throwable $e) {
    $results['test4_db'] = ['ERROR' => $e->getMessage(), 'PASS' => false];
}

// ── TEST 5: Queue check ─────────────────────────────────────────
try {
    $depth = QueueEngine::depth();
    $results['test5_queue'] = [
        'queue_depth' => $depth,
        'PASS' => true,
    ];
} catch (Throwable $e) {
    $results['test5_queue'] = ['ERROR' => $e->getMessage(), 'PASS' => false];
}

// ── SUMMARY ────────────────────────────────────────────────────
$pass_count = count(array_filter($results, fn($r) => $r['PASS'] ?? false));
$total = count($results);

echo json_encode([
    'timestamp' => date('Y-m-d H:i:s'),
    'tests' => $results,
    'summary' => [
        'passed' => $pass_count,
        'total'  => $total,
        'score'  => round($pass_count/$total*100) . '%',
        'status' => $pass_count === $total ? 'ALL_PASS' : 'PARTIAL',
    ],
], JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE);
