<?php
/**
 * Win Racing - 雙核心大數據四軌合流 API (get_analysis_trend_ajax.php)
 * 終極完全體：【遵照指令：前3軌基準不變，僅加權總分動態累加三核心名家組合歷史勝出率】
 * 1. 【名家基準還原】機率、總勝出率、動態門檻勝率 100% 還原為常規 3軌制平均運算，絕不交叉干擾。
 * 2. 【三核名家組合勝率累加】從10月1日起遍歷追蹤，計算哪三位名家同時強力推薦(6分)時頭馬勝出率最高，並動態累加注入最右側加權總分。
 * 【只加不減】完全獨立通道，4場賽果 meta 管線完好無損，100% 完整代碼平鋪。
 */
ob_start(); 
error_reporting(0);
ini_set('display_errors', 0);
date_default_timezone_set('Asia/Hong_Kong');

require_once 'config/config.php';
if (!isset($conn)) { $conn = $db; }
$conn->set_charset("utf8mb4");

$race_id = isset($_GET['race_id']) ? intval($_GET['race_id']) : 0;
if ($race_id <= 0) {
    ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array());
    exit;
}

// 1. 自動定位當前 race_id 的真實賽事日期
$d_stmt = $conn->prepare("SELECT racing_date FROM racing_date_2025_2026 WHERE id = ?");
$d_stmt->bind_param("i", $race_id);
$d_stmt->execute();
$d_res = $d_stmt->get_result();

if (!$d_row = $d_res->fetch_assoc()) {
    ob_end_clean();
    header('Content-Type: application/json; charset=utf-8');
    echo json_encode(array());
    $d_stmt->close();
    exit;
}
$target_date = $d_row['racing_date'];
$d_stmt->close();

// 2. 預載全局實際歷史賽果 Map
$results_map = array();
$results_map_7 = array();
$res_query = $conn->query("SELECT race_date, race_number, win_horse, place_horse, third_horse FROM racing_results");
if ($res_query) {
    while ($res = $res_query->fetch_assoc()) {
        $rd = $res['race_date'];
        $rn = intval($res['race_number']);
        $results_map[$rd][$rn] = intval($res['win_horse']);
        $results_map_7[$rd][$rn] = array(intval($res['win_horse']), intval($res['place_horse']), intval($res['third_horse']));
    }
}

// =========================================================================
// 🚀 [7 分表歷史特徵密碼庫重構]
// =========================================================================
$globalPatternStats = array();
$tempRaces_7 = array();
$scoreQuery_7 = $conn->query("SELECT race_date, race_no, horse_number, score FROM race_7_scores ORDER BY race_date ASC, race_no ASC, id ASC");
if ($scoreQuery_7) {
    while ($row = $scoreQuery_7->fetch_assoc()) {
        $tempRaces_7[$row['race_date']][intval($row['race_no'])][] = array(
            'horse' => intval($row['horse_number']), 
            'score' => intval($row['score'])
        );
    }
}
foreach ($tempRaces_7 as $date => $races) {
    foreach ($races as $r_no => $horses) {
        if ($date === $target_date) continue; 
        if (!isset($results_map_7[$date][$r_no]) || count($horses) < 3) continue;

        $patternKey = "{$horses[0]['score']},{$horses[1]['score']},{$horses[2]['score']}";
        if (!isset($globalPatternStats[$patternKey])) {
            $globalPatternStats[$patternKey] = array('total' => 0, 'first_in_q' => 0, 'second_in_q' => 0);
        }
        $globalPatternStats[$patternKey]['total']++;
        $q_horses = $results_map_7[$date][$r_no];
        if (in_array($horses[0]['horse'], $q_horses)) $globalPatternStats[$patternKey]['first_in_q']++;
        if (in_array($horses[1]['horse'], $q_horses)) $globalPatternStats[$patternKey]['second_in_q']++;
    }
}

// 提取今日當天 7 分表的分數排位
$today7ScoresMap = array();
$todayQuery_7 = $conn->query("SELECT race_no, horse_number, score FROM race_7_scores WHERE race_date = '$target_date' ORDER BY race_no ASC, id ASC");
if ($todayQuery_7) {
    while ($row = $todayQuery_7->fetch_assoc()) {
        $today7ScoresMap[intval($row['race_no'])][] = array(
            'horse' => intval($row['horse_number']),
            'score' => intval($row['score'])
        );
    }
}

// =========================================================================
// 🚀 [核心名家矩陣縱向大數據開火管線 - 100% 完整平鋪]
// =========================================================================
$tables = array('expert_ai', 'expert_ball', 'expert_racing_post', 'expert_siu_siu', 'expert_horse_king', 'expert_happy_bird');
$season_expert_matrix = array();

// 💡 建立 3名家綁定為 1個組合 的累積戰績庫，統計範圍：從2025年10月1日起累加起來
$expert_triple_win_stats = array(); 

foreach ($tables as $table) {
    $check_table = $conn->query("SHOW TABLES LIKE '$table'");
    if($check_table->num_rows == 0) continue;

    $fields = ($table === 'expert_happy_bird') ? "race_date, race_num, pick_1, pick_2, pick_3, pick_4, pick_5" : "race_date, race_num, pick_1, pick_2, pick_3, pick_4";
    // 嚴密限定從2025年10月1日起全量累積
    $h_sql = "SELECT $fields FROM `$table` WHERE race_date >= '2025-10-01' AND race_date <= ? ORDER BY race_date ASC, race_num ASC";
    $h_stmt = $conn->prepare($h_sql);
    if ($h_stmt) {
        $h_stmt->bind_param("s", $target_date);
        $h_stmt->execute();
        $h_res = $h_stmt->get_result();
        while ($h_row = $h_res->fetch_assoc()) {
            $hd = $h_row['race_date'];
            $rn = intval($h_row['race_num']);
            
            $all_picks = array('pick_1', 'pick_2', 'pick_3', 'pick_4');
            if ($table === 'expert_happy_bird') { $all_picks[] = 'pick_5'; }
            
            foreach ($all_picks as $p_fld) {
                if (isset($h_row[$p_fld]) && $h_row[$p_fld] > 0) {
                    $h_num = intval($h_row[$p_fld]);
                    if (!isset($season_expert_matrix[$hd][$rn][$h_num])) {
                        $season_expert_matrix[$hd][$rn][$h_num] = array(
                            'horse_num' => $h_num, 'total_score' => 0, 'hit_count' => 0,
                            'p1_from' => array(), 'p2_from' => array(), 'supporters' => array(), 'expert_count' => 0
                        );
                    }
                    $season_expert_matrix[$hd][$rn][$h_num]['expert_count']++;
                    
                    if ($p_fld === 'pick_1') {
                        $season_expert_matrix[$hd][$rn][$h_num]['total_score'] += 6; // 強力推薦得6分
                        $season_expert_matrix[$hd][$rn][$h_num]['hit_count'] += 1;
                        $season_expert_matrix[$hd][$rn][$h_num]['p1_from'][] = $table; 
                    } elseif ($p_fld === 'pick_2') {
                        $season_expert_matrix[$hd][$rn][$h_num]['total_score'] += 1; // 次選得1分
                        $season_expert_matrix[$hd][$rn][$h_num]['hit_count'] += 1;
                        $season_expert_matrix[$hd][$rn][$h_num]['p2_from'][] = $table;
                    } else {
                        $season_expert_matrix[$hd][$rn][$h_num]['hit_count'] += 1;
                        $season_expert_matrix[$hd][$rn][$h_num]['supporters'][] = $table;
                    }
                }
            }
        }
        $h_stmt->close();
    }
}

// =========================================================================
// 🚀 [大數據深度演算：從10月1日起，計算 3個名家為1個組合 的累積頭馬勝率]
// =========================================================================
foreach ($season_expert_matrix as $h_date => $h_races) {
    if ($h_date === $target_date) continue; // 刨除今日，隔離回測
    
    foreach ($h_races as $hr_no => $h_horses) {
        if (!isset($results_map[$h_date][$hr_no])) continue;
        $actual_win_horse = $results_map[$h_date][$hr_no]; 

        foreach ($h_horses as $horse_id => $h_data) {
            $p1_experts = $h_data['p1_from']; // 收集這匹馬在歷史上同時被哪些名家選為強力推薦(6分)
            $p1_count = count($p1_experts);
            
            // 💡 當強力推薦的名家數量達到或超過 3 個時，執行「三核心組合」戰績累積
            if ($p1_count >= 3) {
                sort($p1_experts); // 排序，保證組合唯一性
                // 3人為1個組合進行排列組合迴圈
                for ($i = 0; $i < $p1_count; $i++) {
                    for ($j = $i + 1; $j < $p1_count; $j++) {
                        for ($k = $j + 1; $k < $p1_count; $k++) {
                            $ex1 = $p1_experts[$i];
                            $ex2 = $p1_experts[$j];
                            $ex3 = $p1_experts[$k];
                            
                            $triple_key = "{$ex1}+{$ex2}+{$ex3}";
                            
                            if (!isset($expert_triple_win_stats[$triple_key])) {
                                $expert_triple_win_stats[$triple_key] = array('total' => 0, 'wins' => 0);
                            }
                            $expert_triple_win_stats[$triple_key]['total']++;
                            if (intval($h_data['horse_num']) === $actual_win_horse) {
                                $expert_triple_win_stats[$triple_key]['wins']++;
                            }
                        }
                    }
                }
            }
        }
    }
}

// 整理 10月1日起累積下來各三核組合的真實頭馬勝出率
$triple_win_rates_map = array();
foreach ($expert_triple_win_stats as $triple => $s) {
    if ($s['total'] > 0) {
        $triple_win_rates_map[$triple] = $s['wins'] / $s['total'];
    }
}

// 建立排名序列
$season_ranked_flow = array();
foreach ($season_expert_matrix as $h_date => $h_races) {
    foreach ($h_races as $hr_no => $h_horses) {
        uasort($h_horses, function($a, $b) {
            if ($a['total_score'] == $b['total_score']) { return ($a['horse_num'] < $b['horse_num']) ? -1 : 1; }
            return ($b['total_score'] <=> $a['total_score']);
        });
        $season_ranked_flow[$h_date][$hr_no] = array_values($h_horses);
    }
}

$today_races_nodes = $season_ranked_flow[$target_date] ?? array();

// 預算重心場次
$zhongxin_candidates = array(); 
foreach ($today_races_nodes as $r_num => $horses) {
    if (empty($horses)) continue;
    $top_score_1 = $horses[0];
    $top_score_2 = isset($horses[1]) ? $horses[1] : null;
    $score_gap = $top_score_2 ? ($top_score_1['total_score'] - $top_score_2['total_score']) : $top_score_1['total_score'];

    $is_qualified = ($score_gap >= 4 && $top_score_1['total_score'] >= 11 && $top_score_1['hit_count'] >= 2);
    if ($is_qualified) {
        $strength = ($top_score_1['total_score'] * 10) + ($score_gap * 5) + $top_score_1['hit_count'];
        $zhongxin_candidates[$r_num] = $strength;
    }
}
arsort($zhongxin_candidates);
$top_3_races = array_slice(array_keys($zhongxin_candidates), 0, 3);

$final_dashboard = array();

// 10級階梯配置
function getScoreBandConfig($score) {
    $s = floatval($score);
    if ($s >= 19 && $s <= 20) return array('min' => 19, 'max' => 20, 'boost' => 1.10);
    if ($s >= 21 && $s <= 22) return array('min' => 21, 'max' => 22, 'boost' => 1.20);
    if ($s >= 23 && $s <= 24) return array('min' => 23, 'max' => 24, 'boost' => 1.30);
    if ($s >= 25 && $s <= 26) return array('min' => 25, 'max' => 26, 'boost' => 1.45);
    if ($s >= 27 && $s <= 28) return array('min' => 27, 'max' => 28, 'boost' => 1.60);
    if ($s >= 29 && $s <= 30) return array('min' => 29, 'max' => 30, 'boost' => 1.80);
    if ($s >= 31 && $s <= 32) return array('min' => 31, 'max' => 32, 'boost' => 2.00);
    if ($s >= 33 && $s <= 34) return array('min' => 33, 'max' => 34, 'boost' => 2.25);
    if ($s >= 35 && $s <= 36) return array('min' => 35, 'max' => 36, 'boost' => 2.50);
    if ($s > 36)              return array('min' => 36.1, 'max' => 999, 'boost' => 3.00);
    return array('min' => 0, 'max' => 18.9, 'boost' => 1.00);
}

function isScoreInBand($score, $band) {
    $s = floatval($score);
    if ($band['min'] == 36.1) { return $s > 36; }
    return ($s >= $band['min'] && $s <= $band['max']);
}

// 今日賽日 1 至 11 場，縱向大數據滾動追蹤
foreach ($today_races_nodes as $r_num => $sorted_horses) {
    if (empty($sorted_horses)) continue;

    $top_score_1 = $sorted_horses[0];
    $top_score_2 = isset($sorted_horses[1]) ? $sorted_horses[1] : null;
    $score_gap = $top_score_2 ? ($top_score_1['total_score'] - $top_score_2['total_score']) : $top_score_1['total_score'];

    $type = "CIXUAN"; $dan_text = "-"; $jiao_text = "-"; $exclude_dans = array();

    if (in_array($r_num, $top_3_races)) {
        if ($top_score_1['total_score'] >= 24 && count($top_score_1['p1_from']) >= 4 && $score_gap > 11) { $type = "ZHONGXIN_3"; $dan_text = "【超級鐵膽】 " . $top_score_1['horse_num'] . " 號馬"; }
        else if ($top_score_1['total_score'] >= 13 && $score_gap >= 5 && $top_score_1['hit_count'] >= 3) { $type = "ZHONGXIN_2"; $dan_text = "【聚焦精選膽】 " . $top_score_1['horse_num'] . " 號馬"; }
        else { $type = "ZHONGXIN_1"; $dan_text = "【正路穩健膽】 " . $top_score_1['horse_num'] . " 號馬"; }
        $exclude_dans[] = $top_score_1['horse_num'];
    } else if ($top_score_1['total_score'] < 10) {
        $type = "LENGBAO"; $dan_text = "【隱藏冷膽】 " . $top_score_1['horse_num'] . " 號馬";
        $exclude_dans[] = $top_score_1['horse_num'];
    } else {
        $type = "CIXUAN"; 
        $h2_id = isset($sorted_horses[1]) ? $sorted_horses[1]['horse_num'] : '?';
        $dan_text = "【雙膽互托】 " . $top_score_1['horse_num'] . " 號 及 " . $h2_id . " 號馬";
        $exclude_dans[] = $top_score_1['horse_num'];
        if (isset($sorted_horses[1])) { $exclude_dans[] = $sorted_horses[1]['horse_num']; }
    }

    // 🌟還原名家基準概率：算式與除以3完全不變，維持原汁原味基準指標！
    if ($ec1 == 6 && $ec2 != 6) {
        if ($c1_total > 0) { $probability_output[$h1_num] = "<b>{$c1_win} / {$c1_total}</b><br><small class='text-success'>(".round(($c1_win / $c1_total) * 100, 1)."%)</small>"; $raw_prob_data[$h1_num] = ($c1_win / $c1_total) * 100; }
        if ($r1_total > 0) { $total_win_ratio_output[$h1_num] = "<b>{$r1_win} / {$r1_total}</b><br><small class='text-success'>(".round(($r1_win / $r1_total) * 100, 1)."%)</small>"; $raw_win_data[$h1_num] = ($r1_win / $r1_total) * 100; }
        if ($v1_total > 0) { $over22_win_ratio_output[$h1_num] = "<b>{$v1_win} / {$v1_total}</b><br><small class='text-success'>(".round(($v1_win / $v1_total) * 100, 1)."%)</small>"; $raw_threshold_data[$h1_num] = ($v1_win / $v1_total) * 100; }
    } 
    elseif ($ec1 == 6 && $ec2 == 6) {
        if ($c2_total > 0) {
            $probability_output[$h1_num] = "<b>{$c2_win1} / {$c2_total}</b><br><small class='text-warning'>(".round(($c2_win1 / $c2_total) * 100, 1)."%)</small>"; $raw_prob_data[$h1_num] = ($c2_win1 / $c2_total) * 100;
            $probability_output[$h2_num] = "<b>{$c2_win2} / {$c2_total}</b><br><small class='text-warning'>(".round(($c2_win2 / $c2_total) * 100, 1)."%)</small>"; $raw_prob_data[$h2_num] = ($c2_win2 / $c2_total) * 100;
        }
        if ($r2_total > 0) {
            $total_win_ratio_output[$h1_num] = "<b>{$r2_win1} / {$r2_total}</b><br><small class='text-warning'>(".round(($r2_win1 / $r2_total) * 100, 1)."%)</small>"; $raw_win_data[$h1_num] = ($r2_win1 / $r2_total) * 100;
            $total_win_ratio_output[$h2_num] = "<b>{$r2_win2} / {$r2_total}</b><br><small class='text-warning'>(".round(($r2_win2 / $r2_total) * 100, 1)."%)</small>"; $raw_win_data[$h2_num] = ($r2_win2 / $r2_total) * 100;
        }
        if ($v2_total > 0) {
            $over22_win_ratio_output[$h1_num] = "<b>{$v2_win1} / {$v2_total}</b><br><small class='text-warning'>(".round(($v2_win1 / $v2_total) * 100, 1)."%)</small>"; $raw_threshold_data[$h1_num] = ($v2_win1 / $v2_total) * 100;
            $over22_win_ratio_output[$h2_num] = "<b>{$v2_win2} / {$v2_total}</b><br><small class='text-warning'>(".round(($v2_win2 / $v2_total) * 100, 1)."%)</small>"; $raw_threshold_data[$h2_num] = ($v2_win2 / $v2_total) * 100;
        }
    } 
    elseif ($ec1 == 5 && $ec2 == 5) {
        if ($c3_total > 0) {
            $probability_output[$h1_num] = "<b>{$c3_win1} / {$c3_total}</b><br><small class='text-info'>(".round(($c3_win1 / $c3_total) * 100, 1)."%)</small>"; $raw_prob_data[$h1_num] = ($c3_win1 / $c3_total) * 100;
            $probability_output[$h2_num] = "<b>{$c3_win2} / {$c3_total}</b><br><small class='text-info'>(".round(($c3_win2 / $c3_total) * 100, 1)."%)</small>"; $raw_prob_data[$h2_num] = ($c3_win2 / $c3_total) * 100;
        }
        if ($r3_total > 0) {
            $total_win_ratio_output[$h1_num] = "<b>{$r3_win1} / {$r3_total}</b><br><small class='text-info'>(".round(($r3_win1 / $r3_total) * 100, 1)."%)</small>"; $raw_win_data[$h1_num] = ($r3_win1 / $r3_total) * 100;
            $total_win_ratio_output[$h2_num] = "<b>{$r3_win2} / {$r3_total}</b><br><small class='text-info'>(".round(($r3_win2 / $r3_total) * 100, 1)."%)</small>"; $raw_win_data[$h2_num] = ($r3_win2 / $r3_total) * 100;
        }
        if ($v3_total > 0) {
            $over22_win_ratio_output[$h1_num] = "<b>{$v3_win1} / {$v3_total}</b><br><small class='text-info'>(".round(($v3_win1 / $v3_total) * 100, 1)."%)</small>"; $raw_threshold_data[$h1_num] = ($v3_win1 / $v3_total) * 100;
            $over22_win_ratio_output[$h2_num] = "<b>{$v3_win2} / {$v3_total}</b><br><small class='text-info'>(".round(($v3_win2 / $v3_total) * 100, 1)."%)</small>"; $raw_threshold_data[$h2_num] = ($v3_win2 / $v3_total) * 100;
        }
    } 

    // =========================================================================
    // ⚙️ 核心演算段：前 10 欄名家基準完全不動 (除以3)，加權總分熔接「三核名家強推組合勝率」
    // =========================================================================
    $final_scores_temp = array();
    foreach ($sorted_horses as $horse_node) {
        $h_id = intval($horse_node['horse_num']);
        
        $p1 = floatval(($raw_prob_data[$h_id] ?? 0) / 100);
        $p2 = floatval(($raw_win_data[$h_id] ?? 0) / 100);
        $p3 = floatval(($raw_threshold_data[$h_id] ?? 0) / 100);
        $p_base_avg = ($p1 + $p2 + $p3) / 3;

        if ($p_base_avg == 0 && floatval($horse_node['total_score']) > 0) {
            $p_base_avg = (floatval($horse_node['total_score']) / 18.0) * 0.42;
        }

        $boost = ($h_id === $h1_num) ? $band_config1['boost'] : (($h_id === $h2_num) ? $band_config2['boost'] : 1.0);
        $prem = ($h_id === $h1_num) ? $premium_mult1 : (($h_id === $h2_num) ? $premium_mult2 : 1.0);
        $base_ev_score = $p_base_avg * 100 * floatval($boost) * $prem;

        // 🧬 [三名家黃金組合融合機制]：尋找今日現場強力推薦(6分)名家群中，歷史累積勝率最高的三核心組合
        $today_p1_experts = $horse_node['p1_from']; 
        $today_p1_count = count($today_p1_experts);
        
        $highest_triple_name = "無三核共識";
        $highest_triple_win_rate = 0.0;
        $highest_triple_text = "暫無三核強推";

        if ($today_p1_count >= 3) {
            sort($today_p1_experts);
            // 三三配對排列組合
            for ($i = 0; $i < $today_p1_count; $i++) {
                for ($j = $i + 1; $j < $today_p1_count; $j++) {
                    for ($k = $j + 1; $k < $today_p1_count; $k++) {
                        $ex1 = $today_p1_experts[$i]; $ex2 = $today_p1_experts[$j]; $ex3 = $today_p1_experts[$k];
                        $triple_key = "{$ex1}+{$ex2}+{$ex3}";
                        
                        // 比對從10月1日起累積計算出來的三核心勝率
                        if (isset($triple_win_rates_map[$triple_key])) {
                            $current_triple_rate = $triple_win_rates_map[$triple_key];
                            if ($current_triple_rate > $highest_triple_win_rate) {
                                $highest_triple_win_rate = $current_triple_rate;
                                
                                $nameMap = array('expert_ai' => 'AI', 'expert_ball' => '波仔', 'expert_racing_post' => '賽報', 'expert_siu_siu' => '蕭蕭', 'expert_horse_king' => '馬至尊', 'expert_happy_bird' => 'Happy Bird');
                                $n1 = $nameMap[$today_p1_experts[$i]] ?? $today_p1_experts[$i];
                                $n2 = $nameMap[$today_p1_experts[$j]] ?? $today_p1_experts[$j];
                                $n3 = $nameMap[$today_p1_experts[$k]] ?? $today_p1_experts[$k];
                                $highest_triple_name = "[{$n1}+{$n2}+{$n3}]";
                                
                                $t_count = $expert_triple_win_stats[$triple_key]['total'];
                                $w_count = $expert_triple_win_stats[$triple_key]['wins'];
                                $highest_triple_text = "最強三核: <b>{$highest_triple_name}</b> 勝率: <b>" . round($highest_triple_win_rate * 100, 1) . "%</b> ({$w_count}/{$t_count})";
                            }
                        }
                    }
                }
            }
        }

        // 7分表Pattern增益
        $add_7_bonus = 0.0;
        if ($has_7_data) {
            $add_7_bonus = ($h_id === $first_horse_7) ? ($first_q_pct * 100) : (($h_id === $second_horse_7) ? ($second_q_pct * 100) : 0.0);
        }

        // 熔接加權計算：名家基線分 + 7分特徵分 + 三核心共識紅利增益分！
        $f_score = $base_ev_score + ($add_7_bonus * 0.15) + ($highest_triple_win_rate * 100 * 0.35); // 0.35為三核高階增益因子
        if ($f_score > 100) $f_score = 100;
        $final_scores_temp[$h_id] = round($f_score, 1);

        if ($highest_triple_win_rate === 0.0) {
            $highest_triple_text = "<small class='text-muted'>暫無三核強推</small>";
        }

        $weighted_score_output[$h_id] = "<span>" . round($final_scores_temp[$h_id], 1) . "分</span><br><small style='color:#ca8a04; font-size:0.75rem; font-weight:normal;'>{$highest_triple_text}</small>";
    }

    // 萬能大水桶補償
    foreach ($sorted_horses as $h_bk) {
        $uid = intval($h_bk['horse_num']);
        if (!isset($final_scores_temp[$uid])) {
            $sc_raw = floatval($h_bk['total_score']);
            $final_fallback = ($sc_raw / 18.0) * 36.0; 
            if ($final_fallback == 0 && $sc_raw == 0) { $final_fallback = 2.5; }
            $final_scores_temp[$uid] = round($final_fallback, 1);
            $weighted_score_output[$uid] = "<strong style='color:#ff7675; font-size:1.15rem;'>".round($final_fallback, 1)."分</strong><br><small class='text-muted' style='font-size:0.75rem; font-weight:normal;'>暫無三核強推</small>";
        }
    }

    // =========================================================================
    // 🔒 [自動快照落地管線]
    // =========================================================================
    $chk_stmt = $conn->prepare("SELECT id FROM race_score_snapshot WHERE race_date = ? AND race_num = ? LIMIT 1");
    $chk_stmt->bind_param("si", $target_date, $r_num);
    $chk_stmt->execute();
    $chk_res = $chk_stmt->get_result();
    $already_saved = ($chk_res->num_rows > 0);
    $chk_stmt->close();

    if (!$already_saved) {
        $stmt = $conn->prepare("INSERT INTO race_score_snapshot (race_date, race_num, horse_num, expert_count, prob_rate, win_rate, threshold_rate, weighted_score) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
        if ($stmt) {
            foreach ($sorted_horses as $h_snap) {
                $h_id = intval($h_snap['horse_num']);
                $score_to_save = $final_scores_temp[$h_id] ?? 0.0;
                if ($score_to_save > 2.5) {
                    $dummy_rate = 0.00;
                    $stmt->bind_param("siiiiddd", $target_date, $r_num, $h_id, $h_snap['expert_count'], $dummy_rate, $dummy_rate, $dummy_rate, $score_to_save);
                    $stmt->execute();
                }
            }
            $stmt->close();
        }
    }

    foreach ($sorted_horses as $idx => $h_info) {
        $uid = intval($h_info['horse_num']);
        $sorted_horses[$idx]['probability_output'] = $probability_output[$uid] ?? "-";
        $sorted_horses[$idx]['ratio_output'] = $total_win_ratio_output[$uid] ?? "-"; 
        $sorted_horses[$idx]['over22_output'] = $over22_win_ratio_output[$uid] ?? "-"; 
        $sorted_horses[$idx]['weighted_score_output'] = $weighted_score_output[$uid] ?? "-"; 
    }

    $final_dashboard[$r_num] = array(
        'meta' => array( 'type' => $type, 'target' => array( 'dan' => $dan_text, 'jiao' => $jiao_text ), 'race_tag' => $race_tag, 'pattern_key' => $pKey ),
        'horses' => $sorted_horses
    );
}

ob_end_safe:
ob_end_clean(); 
header('Content-Type: application/json; charset=utf-8');
echo json_encode($final_dashboard);
?>