<?php
require_once __DIR__ . '/runtime/wr_bootstrap.php';
@set_time_limit(1200);
@ini_set('memory_limit', '1536M');
require_once __DIR__ . '/config/config.php';
if (!wr_db_guard_normalize()) {
    throw new RuntimeException('DB connection unavailable');
}
require_once __DIR__ . '/Chairman/supreme/ChairmanSupremeDecisionEngineV51.php';

function wr_v51_h($value)
{
    return htmlspecialchars((string)$value, ENT_QUOTES, 'UTF-8');
}

function wr_v51_resolve_race_date()
{
    $candidates = array('race_date', 'date', 'review_date');
    foreach ($candidates as $key) {
        if (!isset($_GET[$key])) {
            continue;
        }
        $value = trim((string)$_GET[$key]);
        $dt = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
        $errors = DateTimeImmutable::getLastErrors();
        $valid = $dt instanceof DateTimeImmutable
            && ($errors === false || ((int)$errors['warning_count'] === 0 && (int)$errors['error_count'] === 0))
            && $dt->format('Y-m-d') === $value;
        if ($valid) {
            return $value;
        }
    }
    return (new DateTimeImmutable('now', new DateTimeZone('Asia/Hong_Kong')))->format('Y-m-d');
}

$date = wr_v51_resolve_race_date();
$venue = isset($_GET['venue']) ? trim((string)$_GET['venue']) : '';
$venue = preg_replace('/[^A-Za-z0-9_\-]/', '', $venue);
$action = isset($_GET['action']) ? trim((string)$_GET['action']) : 'latest';
$engine = new ChairmanSupremeDecisionEngineV51($conn);
$data = $action === 'build' ? $engine->build($date, $venue) : $engine->latest($date, $venue);
$day = isset($data['day']) && is_array($data['day']) ? $data['day'] : array();
$races = isset($data['races']) && is_array($data['races']) ? $data['races'] : array();
?>
<!doctype html>
<html lang="zh-Hant">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>WinRacing V51 Supreme Decision</title>
<style>
body{margin:0;background:#050914;color:#eef6ff;font-family:Arial,'Microsoft JhengHei',sans-serif;font-size:13px}.wrap{max-width:1880px;margin:auto;padding:22px}.hero,.panel{background:#0b1424;border:1px solid #31486b;border-radius:14px;padding:16px;margin-bottom:14px}.gold{color:#ffc107}.green{color:#36f2a3}.cyan{color:#5edbff}.red{color:#ff7589}.muted{color:#9eb0c7}.grid{display:grid;grid-template-columns:repeat(3,minmax(0,1fr));gap:12px}.card{background:#08101d;border:1px solid #2c405c;border-radius:12px;padding:13px}.badge{display:inline-block;padding:3px 8px;border-radius:999px;background:#162942;border:1px solid #36577e;font-weight:700}.score{font-size:24px;font-weight:900}input{background:#07111f;color:#fff;border:1px solid #345;padding:8px}button{background:#ffc107;border:0;padding:9px 14px;font-weight:900;border-radius:6px}.empty{padding:28px;text-align:center;color:#ffcf66}@media(max-width:1100px){.grid{grid-template-columns:1fr 1fr}}@media(max-width:700px){.grid{grid-template-columns:1fr}}
</style>
</head>
<body><div class="wrap">
<div class="hero"><h1>🏆 V51 — <span class="gold">Supreme Decision</span></h1><div class="muted">V50 Ultimate → calibration / governance → Supreme action. Read-only DB; no schema migration.</div></div>
<div class="panel"><form method="get" action="">Race Date <input type="date" name="race_date" value="<?=wr_v51_h($date)?>"> <strong class="cyan">Selected: <?=wr_v51_h($date)?></strong> Venue <input name="venue" value="<?=wr_v51_h($venue)?>"> <button name="action" value="build">Build V51 Snapshot</button></form></div>
<?php if (isset($data['message']) && $data['message'] !== ''): ?><div class="panel <?=($data['status']==='OK'?'green':'gold')?>"><?=wr_v51_h($data['message'])?></div><?php endif; ?>
<?php if ($day): ?>
<div class="panel"><h2>Supreme Daily Summary</h2><div class="grid">
<div class="card"><small>Best Supreme Banker</small><div class="score gold">R<?=wr_v51_h($day['best_banker_race'])?> #<?=wr_v51_h($day['best_banker_horse'])?></div><div><?=wr_v51_h($day['best_banker_name'])?></div><p><span class="badge"><?=wr_v51_h($day['best_banker_tier'])?></span> Score <?=number_format((float)$day['best_banker_score'],1)?></p></div>
<div class="card"><small>Portfolio State</small><div class="score green"><?=number_format((float)$day['portfolio_confidence'],1)?></div><div><?=wr_v51_h($day['portfolio_state'])?></div><p>Strong: <?=wr_v51_h($day['strong_bankers'])?></p></div>
<div class="card"><small>Top 3 / Skip</small><h3 class="cyan"><?=wr_v51_h($day['top3_bankers'])?></h3><p class="red">Skip: <?=wr_v51_h($day['skip_races'])?></p></div>
</div></div>
<?php endif; ?>
<div class="panel"><h2>Supreme Race Decisions</h2>
<?php if (!$races): ?><div class="empty">No V50 source data for this date. Build V50 first.</div><?php else: ?><div class="grid">
<?php foreach ($races as $race): ?>
<div class="card"><h3 class="gold">R<?=wr_v51_h($race['race_num'])?>｜#<?=wr_v51_h($race['banker_horse'])?> <?=wr_v51_h($race['banker_name'])?></h3>
<div class="score"><?=number_format((float)$race['supreme_confidence'],1)?></div><p><span class="badge"><?=wr_v51_h($race['supreme_tier'])?></span> Action <?=wr_v51_h($race['supreme_action'])?></p>
<p>V50 <?=number_format((float)$race['v50_ultimate_confidence'],1)?>｜Gap <?=number_format((float)$race['confidence_gap'],1)?>｜Risk -<?=number_format((float)$race['risk_penalty'],1)?></p>
<p>Consensus <?=number_format((float)$race['consensus_pct'],1)?>｜RSI <?=number_format((float)$race['stability_index'],1)?>｜Stars <?=wr_v51_h($race['star_rating'])?></p>
<p>Q <?=wr_v51_h($race['q_top2'])?>｜Top4 <?=wr_v51_h($race['trio_top4'])?></p><p>Value <?=wr_v51_h($race['value_horses'])?>｜Avoid <?=wr_v51_h($race['avoid_horses'])?></p></div>
<?php endforeach; ?></div><?php endif; ?></div>
</div></body></html>
