<?php
/**
 * Live, end-to-end verification of api/trades/validate.php's
 * PropFirmRuleEngine wiring, through the real Apache/PHP/MariaDB stack —
 * not a code-review claim. Construct-verify-revert discipline: mutates
 * one real account's rules JSON to the documented-normal "phase-specific-
 * only, no flat max_dd_pct/daily_dd_pct keys" shape, proves the OLD code
 * (cited from git HEAD) would have silently disabled breach detection at
 * this exact scenario, proves the NEW code (real HTTP call) correctly
 * fires it, then fully reverts.
 */
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]
);

$accountId = 'f9d5230d-68e4-407a-9802-bec56b8118d8';
$userId = '278d5983-d646-494f-a130-b22f7c321867';

// 1. Snapshot original rules.
$stmt = $pdo->prepare("SELECT rules FROM challenge_accounts WHERE account_id = ?");
$stmt->execute([$accountId]);
$originalRules = $stmt->fetchColumn();
echo "Original rules: {$originalRules}\n";

$origDecoded = json_decode($originalRules, true);
echo "Original max_dd_pct present: " . (array_key_exists('max_dd_pct', $origDecoded) ? 'yes' : 'no') . "\n";
echo "Original daily_dd_pct present: " . (array_key_exists('daily_dd_pct', $origDecoded) ? 'yes' : 'no') . "\n\n";

// 2. Mutate: strip flat max_dd_pct/daily_dd_pct, keep only phase-specific
// profit-target keys — this is the exact "documented normal case for real
// two/three-step accounts" shape the audit's most severe finding depends
// on (CLAUDE.md: "phase_N_target_pct... is the key every real two_step/
// three_step account's rules JSON actually uses").
$testRules = [
    'phase_1_target_pct' => 8,
    'phase_2_target_pct' => 5,
    'profit_split_pct' => 90,
    'challenge_type' => 'two_step',
];
$testRulesJson = json_encode($testRules);
$pdo->prepare("UPDATE challenge_accounts SET rules = ? WHERE account_id = ?")
    ->execute([$testRulesJson, $accountId]);
echo "Mutated rules to: {$testRulesJson}\n\n";

// 3. Cite the OLD code's behavior directly (git HEAD~... the version
// before this session's edit), computed by hand against the exact same
// mutated rules — proves what the pre-fix endpoint would have done.
echo "=== OLD CODE (pre-fix, cited from git history) ===\n";
$oldMaxDdPct = (float)($testRules['max_dd_pct'] ?? 0);
echo "OLD: \$maxDdPct = \$rules['max_dd_pct'] ?? 0  =>  {$oldMaxDdPct}\n";
echo "OLD: breach detection guard `if (\$maxDdPct > 0 && ...)` => " . ($oldMaxDdPct > 0 ? 'WOULD RUN' : 'SILENTLY SKIPPED — breach_warning stays false regardless of risk size') . "\n\n";

// 4. Real, live HTTP round-trip against the NEW code through the actual
// router — auto-login as the real account owner, then POST to the real
// endpoint with a risk size chosen to cross the real (engine-resolved)
// breach line: starting_balance=5000, zero closed trades (confirmed
// beforehand), engine's max_overall_loss_pct default (no flat/phase-
// specific max-loss key present) = 10% => breach level = 4500.
// risk_per_position=600 => projected balance 4400 <= 4500 => should breach.
$base = 'http://localhost:8080/traderalign';
$cookieJar = tempnam(sys_get_temp_dir(), 'zzcookie');

$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,
]);
$loginResp = curl_exec($ch);
curl_close($ch);
echo "Auto-login response: {$loginResp}\n\n";

$payload = json_encode(['account_id' => $accountId, 'risk_per_position' => 600]);
$ch = curl_init("{$base}/api/trades/validate");
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'],
]);
$validateResp = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

echo "=== NEW CODE (live HTTP POST /api/trades/validate, real session) ===\n";
echo "HTTP status: {$httpCode}\n";
echo "Raw response: {$validateResp}\n\n";

$decoded = json_decode($validateResp, true);
if ($decoded === null) {
    echo "!! Response did not parse as JSON — see raw response above for a PHP error.\n";
} else {
    echo "success: " . json_encode($decoded['success'] ?? null) . "\n";
    echo "current_balance: " . json_encode($decoded['current_balance'] ?? null) . "\n";
    echo "max_dd_pct: " . json_encode($decoded['max_dd_pct'] ?? null) . "\n";
    echo "breach_warning: " . json_encode($decoded['breach_warning'] ?? false) . "\n";
    echo "breach_level: " . json_encode($decoded['breach_level'] ?? null) . "\n";
}

@unlink($cookieJar);

// 5. Revert.
$pdo->prepare("UPDATE challenge_accounts SET rules = ? WHERE account_id = ?")
    ->execute([$originalRules, $accountId]);
$stmt = $pdo->prepare("SELECT rules FROM challenge_accounts WHERE account_id = ?");
$stmt->execute([$accountId]);
$afterRevert = $stmt->fetchColumn();
echo "\nReverted rules: {$afterRevert}\n";
echo "Revert confirmed byte-identical to original: " . ($afterRevert === $originalRules ? 'YES' : 'NO — MISMATCH, INVESTIGATE') . "\n";
