<?php
/**
 * Dry-run verification for TradeClassificationEngine — reads real data,
 * writes nothing. Prints before/after classification counts across every
 * real account, plus a hand-checkable detail dump for a handful of
 * specific trades.
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/TradeClassificationEngine.php';

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

$accounts = $pdo->query("SELECT DISTINCT account_id FROM trades WHERE status='closed' AND deleted_at IS NULL AND account_id IS NOT NULL")->fetchAll();

$oldCounts = [];
$newCounts = [];
$errors = [];
$allResults = []; // tradeId => new result, across all accounts

foreach ($accounts as $row) {
    $accountId = $row['account_id'];
    try {
        $results = TradeClassificationEngine::classifyAccount($accountId, $pdo);
    } catch (\Throwable $e) {
        $errors[] = "$accountId: " . $e->getMessage();
        continue;
    }
    foreach ($results as $tradeId => $r) {
        $allResults[$tradeId] = $r;
        $newCounts[$r['classification']] = ($newCounts[$r['classification']] ?? 0) + 1;
    }
}

$oldRows = $pdo->query("SELECT id, trade_classification FROM trades WHERE status='closed' AND deleted_at IS NULL")->fetchAll();
foreach ($oldRows as $r) {
    $c = $r['trade_classification'] ?? 'NULL';
    $oldCounts[$c] = ($oldCounts[$c] ?? 0) + 1;
}

echo "=== ERRORS (" . count($errors) . ") ===\n";
foreach ($errors as $e) echo "  $e\n";

echo "\n=== OLD (sp_classify_trade) counts ===\n";
foreach ($oldCounts as $c => $n) echo "  $c: $n\n";

echo "\n=== NEW (TradeClassificationEngine, dry-run) counts ===\n";
foreach ($newCounts as $c => $n) echo "  $c: $n\n";

echo "\n=== Trades classified by new engine but missing from old rows / vice versa ===\n";
echo "  Total old rows: " . count($oldRows) . "\n";
echo "  Total new results: " . count($allResults) . "\n";

// Change matrix: old -> new, for every trade the new engine touched
$changeMatrix = [];
foreach ($oldRows as $r) {
    $old = $r['trade_classification'] ?? 'NULL';
    if (!isset($allResults[$r['id']])) continue;
    $new = $allResults[$r['id']]['classification'];
    $key = "$old -> $new";
    $changeMatrix[$key] = ($changeMatrix[$key] ?? 0) + 1;
}
echo "\n=== Change matrix (old -> new) ===\n";
arsort($changeMatrix);
foreach ($changeMatrix as $k => $n) echo "  $k: $n\n";

// Detail dump: pick 5 trades that were 'revenge_trade' under OLD logic
// but are NOT under NEW logic, and 5 that are 'revenge_trade' under BOTH,
// for manual hand-verification.
echo "\n=== Sample: OLD=revenge_trade, NEW=something else (should be the common case) ===\n";
$shown = 0;
foreach ($oldRows as $r) {
    if (($r['trade_classification'] ?? '') !== 'revenge_trade') continue;
    if (!isset($allResults[$r['id']])) continue;
    $new = $allResults[$r['id']];
    if ($new['classification'] === 'revenge_trade') continue;
    echo "  trade {$r['id']}: OLD=revenge_trade NEW={$new['classification']} reason=" . json_encode($new['reason']) . "\n";
    $shown++;
    if ($shown >= 5) break;
}

echo "\n=== Sample: NEW=revenge_trade (should be rare, and each one should show over_risked=true, preceded_by=loss) ===\n";
$shown = 0;
foreach ($allResults as $tradeId => $r) {
    if ($r['classification'] !== 'revenge_trade') continue;
    echo "  trade $tradeId: reason=" . json_encode($r['reason']) . "\n";
    $shown++;
    if ($shown >= 8) break;
}

echo "\n=== Sample: NEW=tilt_warning (fear of trading — should show under_risked=true, preceded_by=loss) ===\n";
$shown = 0;
foreach ($allResults as $tradeId => $r) {
    if ($r['classification'] !== 'tilt_warning') continue;
    echo "  trade $tradeId: reason=" . json_encode($r['reason']) . "\n";
    $shown++;
    if ($shown >= 8) break;
}

echo "\n=== Sample: NEW=loss_high_risk (single-trade over-risk, no loss-before-loss context) ===\n";
$shown = 0;
foreach ($allResults as $tradeId => $r) {
    if ($r['classification'] !== 'loss_high_risk') continue;
    echo "  trade $tradeId: reason=" . json_encode($r['reason']) . "\n";
    $shown++;
    if ($shown >= 5) break;
}

echo "\nDONE.\n";
