<?php
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/JourneySegmentation.php';
require_once __DIR__ . '/../api/analytics/engine.php';
require_once __DIR__ . '/../api/analytics/edge_health_engine.php';

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

// All-time range (message isn't time-bound, matches getAllTimeRange()'s real bounds)
$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]
);
$range = $pdo->prepare("SELECT MIN(captured_at) mn, MAX(captured_at) mx FROM trades WHERE user_id = ?");
$range->execute([$userId]);
$r = $range->fetch();
$from = $r['mn'];
$to = $r['mx'];

// Real NEW value
$factors = AnalyticsEngine::getUserAccounts($userId); // just to confirm engine loads ok
$edgeFactors = EdgeHealthEngine::getPeriodFactors($userId, 'all', $from, $to);
echo "NEW EdgeHealthEngine consistency_score: " . json_encode($edgeFactors['consistency_score']) . " (n={$edgeFactors['n']}, tier={$edgeFactors['tier']})\n";
$expectedBucket = $edgeFactors['consistency_score'] === null ? 'unknown'
    : ($edgeFactors['consistency_score'] >= 80 ? 'Excellent' : ($edgeFactors['consistency_score'] >= 50 ? 'Good' : 'Poor'));
echo "Expected bucket: {$expectedBucket}\n\n";

// OLD value — reproduced by hand: raw stddev over last 100 trades' risk_pct (not time-bound => recentTradesLimit=100, getRecentTrades)
$recentTrades = AnalyticsEngine::getRecentTrades($userId, $from, $to, 100);
$riskValues = [];
foreach ($recentTrades as $t) { if (!empty($t['risk_pct'])) $riskValues[] = (float)$t['risk_pct']; }
if (count($riskValues) >= 3) {
    $avg = array_sum($riskValues) / count($riskValues);
    $variance = array_sum(array_map(fn($r) => pow($r - $avg, 2), $riskValues)) / count($riskValues);
    $stdDev = sqrt($variance);
    $oldBucket = $stdDev < 0.5 ? 'excellent' : ($stdDev < 1.5 ? 'good' : 'poor');
    echo "OLD (raw stddev over last 100 trades) stdDev={$stdDev}, bucket={$oldBucket}\n\n";
} else {
    echo "OLD: fewer than 3 recent trades with risk data\n\n";
}

// Live HTTP round trip
$base = 'http://localhost:8080/traderalign';
$cookieJar = tempnam(sys_get_temp_dir(), 'zzcookie17');
$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' => 'how was my discipline this year']);
$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;
$riskConsistencyValue = null;
foreach (($decoded['cards'][0]['stats'] ?? []) as $stat) {
    if (($stat['label'] ?? '') === 'Risk Consistency') { $riskConsistencyValue = $stat['value']; }
}
echo "Live 'Risk Consistency' card value: " . ($riskConsistencyValue ?? 'NOT FOUND') . "\n";
echo ($riskConsistencyValue === $expectedBucket) ? "PASS\n" : "!!! MISMATCH (expected {$expectedBucket})\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";
}
