<?php
/**
 * Live verification of api/colex/chat.php's generateGeneralResponse()
 * phase-aware total-balance fix. Confirms ANTHROPIC_API_KEY is unset
 * (safe — the rule-based fallback path runs, no real external API call),
 * computes what the OLD raw-sum formula and the NEW phase-aware formula
 * each produce independently, then confirms the live chat response's
 * "Total Balance" card matches the NEW figure.
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/JourneySegmentation.php';
require_once __DIR__ . '/../src/PropFirmRuleEngine.php';

echo "ANTHROPIC_API_KEY configured: " . (defined('ANTHROPIC_API_KEY') && ANTHROPIC_API_KEY ? 'YES (would call real API — abort)' : 'no (safe, rule-based fallback path)') . "\n\n";
if (defined('ANTHROPIC_API_KEY') && ANTHROPIC_API_KEY) { exit(1); }

$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';

$accounts = $pdo->prepare("SELECT id, account_type, current_balance FROM trading_accounts WHERE user_id = ? AND is_active = 1");
$accounts->execute([$userId]);
$accountRows = $accounts->fetchAll();

$oldTotal = 0.0;
$newTotal = 0.0;
$propFirmCount = 0;
$changedAccounts = 0;
foreach ($accountRows as $acc) {
    $raw = (float)$acc['current_balance'];
    $oldTotal += $raw;
    if ($acc['account_type'] === 'prop_firm') {
        $propFirmCount++;
        $pfr = PropFirmRuleEngine::compute($acc['id']);
        $phaseVal = !isset($pfr['error']) ? (float)$pfr['phase_balance'] : $raw;
        $newTotal += $phaseVal;
        if (abs($phaseVal - $raw) > 0.01) $changedAccounts++;
    } else {
        $newTotal += $raw;
    }
}

echo "Total active accounts: " . count($accountRows) . " ({$propFirmCount} prop-firm)\n";
echo "Accounts where phase-aware balance differs from raw current_balance: {$changedAccounts}\n";
echo "OLD (raw sum) total balance: \$" . number_format($oldTotal, 2) . "\n";
echo "NEW (phase-aware sum) total balance: \$" . number_format($newTotal, 2) . "\n";
echo "Difference: \$" . number_format($oldTotal - $newTotal, 2) . "\n\n";

// ── Real, live HTTP round trip through the actual chat endpoint ─────────
$base = 'http://localhost:8080/traderalign';
$cookieJar = tempnam(sys_get_temp_dir(), 'zzcookie15');

$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' => 'hi there, just checking in']);
$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 "=== Live POST /api/colex/chat (message='hi there, just checking in') ===\n";
echo "HTTP {$code}\n";
echo "RAW RESPONSE:\n{$resp}\n\n";
$decoded = json_decode($resp, true);
if ($decoded === null) {
    echo "!!! Non-JSON response.\n";
    exit(1);
}
$conversationId = $decoded['conversation_id'] ?? null;
$cardBalance = null;
foreach (($decoded['cards'][0]['stats'] ?? []) as $stat) {
    if (($stat['label'] ?? '') === 'Total Balance') { $cardBalance = $stat['value'] ?? null; }
}
echo "Message text: " . ($decoded['message'] ?? '(none)') . "\n";
echo "Card 'Total Balance' value: " . ($cardBalance ?? 'NOT FOUND') . "\n\n";

$expectedFormatted = '$' . number_format($newTotal, 2);
echo ($cardBalance === $expectedFormatted)
    ? "PASS — live response's Total Balance ({$cardBalance}) matches the independently-computed phase-aware sum ({$expectedFormatted}), not the old raw sum (\$" . number_format($oldTotal, 2) . ").\n"
    : "!!! MISMATCH — got {$cardBalance}, expected {$expectedFormatted}\n";

// ── Cleanup: delete the conversation/message this test created ──────────
if ($conversationId) {
    $pdo->prepare("DELETE FROM colex_messages WHERE conversation_id = ?")->execute([$conversationId]);
    $pdo->prepare("DELETE FROM colex_conversations WHERE id = ?")->execute([$conversationId]);
    $check = $pdo->prepare("SELECT COUNT(*) FROM colex_conversations WHERE id = ?");
    $check->execute([$conversationId]);
    echo "\nCleanup: conversation {$conversationId} deleted, confirmed gone: " . ((int)$check->fetchColumn() === 0 ? 'YES' : 'NO — STILL EXISTS') . "\n";
}
