<?php
require_once __DIR__ . '/../config/config.php';

$pdo = new PDO(
    "mysql:host=" . DB_HOST . ";port=" . DB_PORT . ";dbname=" . DB_NAME . ";charset=utf8mb4",
    DB_USER, DB_PASS,
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC]
);

$userId = '278d5983-d646-494f-a130-b22f7c321867';

$base = 'http://localhost:8080/traderalign';
$cookieJar = tempnam(sys_get_temp_dir(), 'zzcookie22');
$ch = curl_init("{$base}/public/_zz_test_autologin.php?uid=" . urlencode($userId));
curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEJAR => $cookieJar, CURLOPT_COOKIEFILE => $cookieJar]);
curl_exec($ch);
curl_close($ch);

$payload = json_encode(['message' => 'show my behavior patterns']);
$ch = curl_init("{$base}/api/colex/chat");
curl_setopt_array($ch, [
    CURLOPT_RETURNTRANSFER => true, CURLOPT_COOKIEJAR => $cookieJar, CURLOPT_COOKIEFILE => $cookieJar,
    CURLOPT_POST => true, CURLOPT_POSTFIELDS => $payload, CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
]);
$resp = curl_exec($ch);
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
@unlink($cookieJar);

echo "HTTP {$code}\n";
$decoded = json_decode($resp, true);
$conversationId = $decoded['conversation_id'] ?? null;
echo "Message: " . ($decoded['message'] ?? '(none)') . "\n\n";

foreach (($decoded['cards'][0]['stats'] ?? []) as $key => $stat) {
    echo "  {$stat['label']}: {$stat['value']}\n";
}

echo "\nExpected: message mentions real revenge_trade/tilt_warning counts (17 revenge, 83 tilt all-time for this user), 'Revenge/Tilt Trades' stat = 100 (17+83).\n";

if ($conversationId) {
    $pdo->prepare("DELETE FROM colex_messages WHERE conversation_id = ?")->execute([$conversationId]);
    $pdo->prepare("DELETE FROM colex_conversations WHERE id = ?")->execute([$conversationId]);
    echo "\nCleanup done.\n";
}
