<?php
/**
 * Follow-up detail check on the 10 "mismatches" from the Wave 3e sweep —
 * for each, determine whether rnBuildJourney()'s override SHOULD have
 * applied (PropFirmRuleEngine's phase_label matches the account's real
 * terminal/displayed segment label) or correctly did NOT apply (a
 * historical segment, or a breached/generic 'Current Phase' label that
 * structurally can never match a real segment label).
 */
require_once __DIR__ . '/../config/config.php';
require_once __DIR__ . '/../src/JourneySegmentation.php';
require_once __DIR__ . '/../src/PropFirmRuleEngine.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]
);

$mismatchIds = [
    'aa67d947-235c-426a-a091-02e00c3a5d0b',
    'e645ba9b-d5db-4625-87d6-f3a4d375f063',
    '90743816-4805-4a00-a5a2-46e30c71c32b',
    'ed1ec54e-cc94-480c-9629-d016beee335f',
    'fa1d6f58-2a37-48b4-9f63-1a09ac98cdb5',
    '4bbacee5-fedf-4328-a2ca-6a07f55fbd43',
    '805e3313-dca0-4da4-9b7a-733f0150339c',
    'd61836dc-524a-4352-997c-1dfd3a1c35aa',
    'a6cab620-35ca-40f2-8edf-cd82e7afb685',
    '98d260c0-4e8e-4e84-91e7-b36482a7d690',
];

foreach ($mismatchIds as $accountId) {
    $acc = $pdo->prepare("SELECT ta.label, ta.lifecycle_state, ta.account_type, ca.challenge_type FROM trading_accounts ta JOIN challenge_accounts ca ON ca.account_id = ta.id WHERE ta.id = ?");
    $acc->execute([$accountId]);
    $accRow = $acc->fetch();

    $lifecycleState = $accRow['lifecycle_state'];
    $currentLabel = match (true) {
        str_contains($lifecycleState, 'phase_1') => 'Phase 1',
        str_contains($lifecycleState, 'phase_2') => 'Phase 2',
        str_contains($lifecycleState, 'phase_3') => 'Phase 3',
        $lifecycleState === 'funded_active'       => 'Funded Account',
        default                                    => 'Current Phase',
    };

    $trades = $pdo->prepare("SELECT id, closed_at, captured_at, prop_firm_funded, prop_firm_phase, prop_phase_at_entry, COALESCE(challenge_pnl, broker_pnl, projected_pnl, 0) AS effective_pnl FROM trades WHERE account_id=? AND status='closed' AND deleted_at IS NULL AND (is_validation=0 OR is_validation IS NULL) ORDER BY captured_at ASC");
    $trades->execute([$accountId]);
    $allTrades = $trades->fetchAll();

    $buckets = JourneySegmentation::partitionAccountJourney($allTrades, $accRow['challenge_type'] ?? null, $currentLabel);
    $terminalLabel = array_key_last($buckets);

    $pfr = PropFirmRuleEngine::compute($accountId);
    $pfrLabel = $pfr['phase_label'] ?? '(error)';

    $shouldOverride = ($terminalLabel === $pfrLabel);

    echo "{$accountId} ({$accRow['label']}) lifecycle={$lifecycleState} type={$accRow['challenge_type']}\n";
    echo "  rnBuildJourney's displayed/terminal segment label: {$terminalLabel}\n";
    echo "  PropFirmRuleEngine's real current phase_label:     {$pfrLabel}\n";
    echo "  Override SHOULD apply (labels match): " . ($shouldOverride ? 'YES — this would be a REAL bug if page doesn\'t show canonical value' : 'NO — correctly a historical/non-current segment, local calc is right, page SHOULD differ from PropFirmRuleEngine') . "\n\n";
}
