<?php
/**
 * WinRacing V46 — Chairman Gateway Presenter
 * Converts SafeLoader payload into stable dashboard presentation data.
 * PHP 7.4 compatible.
 */
class ChairmanGatewayPresenter {
    private function n($v, $d=0) {
        return is_numeric($v) ? (float)$v : $d;
    }

    private function s($v, $d='') {
        return ($v === null || $v === '') ? $d : (string)$v;
    }

    public function present(array $payload) {
        $ranking = isset($payload['ranking']) && is_array($payload['ranking'])
            ? $payload['ranking'] : array();

        $summary = isset($payload['summary']) && is_array($payload['summary'])
            ? $payload['summary'] : array();

        $decision = isset($payload['decision']) && is_array($payload['decision'])
            ? $payload['decision'] : array();

        $byRace = array();

        foreach ($ranking as $row) {
            $raceNum = isset($row['race_num']) ? (int)$row['race_num'] : 0;
            if ($raceNum <= 0) continue;

            $score = isset($row['ensemble_score'])
                ? $this->n($row['ensemble_score'])
                : $this->n(isset($row['calibrated_score']) ? $row['calibrated_score'] : 0);

            $rank = isset($row['v44_rank'])
                ? (int)$row['v44_rank']
                : (int)(isset($row['race_rank']) ? $row['race_rank'] : 999);

            if (!isset($byRace[$raceNum])) $byRace[$raceNum] = array();

            $byRace[$raceNum][] = array(
                'horse_num' => $this->s(isset($row['horse_num']) ? $row['horse_num'] : ''),
                'horse_name' => $this->s(isset($row['horse_name']) ? $row['horse_name'] : ''),
                'score' => round($score, 2),
                'rank' => $rank,
                'role' => $this->s(
                    isset($row['final_pick_type']) ? $row['final_pick_type'] :
                    (isset($row['role_tag']) ? $row['role_tag'] : '')
                ),
                'decision' => $this->s(isset($row['final_decision']) ? $row['final_decision'] : 'WATCH'),
                'risk' => round($this->n(isset($row['risk_score']) ? $row['risk_score'] : 0), 2),
                'confidence' => round($this->n(isset($row['confidence_score']) ? $row['confidence_score'] : 0), 2),
                'reason' => $this->s(isset($row['reason_zh']) ? $row['reason_zh'] : '')
            );
        }

        ksort($byRace);

        $summaryMap = array();
        foreach ($summary as $row) {
            $rn = isset($row['race_num']) ? (int)$row['race_num'] : 0;
            if ($rn > 0) $summaryMap[$rn] = $row;
        }

        $decisionMap = array();
        foreach ($decision as $row) {
            $rn = isset($row['race_num']) ? (int)$row['race_num'] : 0;
            if ($rn > 0) $decisionMap[$rn] = $row;
        }

        $races = array();
        $allTop = array();

        foreach ($byRace as $raceNum => $horses) {
            usort($horses, function($a, $b) {
                if ($a['score'] == $b['score']) return $a['rank'] <=> $b['rank'];
                return $a['score'] < $b['score'] ? 1 : -1;
            });

            $top = isset($horses[0]) ? $horses[0] : array();
            $second = isset($horses[1]) ? $horses[1] : array();
            $third = isset($horses[2]) ? $horses[2] : array();
            $fourth = isset($horses[3]) ? $horses[3] : array();

            $raceSummary = isset($summaryMap[$raceNum]) ? $summaryMap[$raceNum] : array();
            $raceDecision = isset($decisionMap[$raceNum]) ? $decisionMap[$raceNum] : array();

            $card = array(
                'race_num' => $raceNum,
                'top' => $top,
                'top2' => array_values(array_filter(array($top, $second))),
                'top4' => array_values(array_filter(array($top, $second, $third, $fourth))),
                'race_mode' => $this->s(
                    isset($raceDecision['race_mode']) ? $raceDecision['race_mode'] :
                    (isset($raceSummary['race_mode']) ? $raceSummary['race_mode'] : 'BALANCED')
                ),
                'race_hint' => $this->s(isset($raceSummary['race_hint']) ? $raceSummary['race_hint'] : ''),
                'rci' => round($this->n(isset($raceDecision['race_confidence_index']) ? $raceDecision['race_confidence_index'] : 0), 2),
                'banker' => $this->s(
                    isset($raceDecision['banker_horse']) ? $raceDecision['banker_horse'] :
                    (isset($top['horse_num']) ? $top['horse_num'] : '')
                ),
                'three_legs' => $this->s(isset($raceDecision['three_legs']) ? $raceDecision['three_legs'] : ''),
                'sixup_top2' => $this->s(isset($raceDecision['sixup_top2']) ? $raceDecision['sixup_top2'] : ''),
                'cold_legs' => $this->s(isset($raceDecision['cold_legs']) ? $raceDecision['cold_legs'] : ''),
                'summary' => $this->s(
                    isset($raceDecision['decision_summary']) ? $raceDecision['decision_summary'] :
                    (isset($raceSummary['reason_zh']) ? $raceSummary['reason_zh'] : '')
                )
            );

            $races[] = $card;

            if ($top) {
                $allTop[] = array(
                    'race_num' => $raceNum,
                    'horse_num' => isset($top['horse_num']) ? $top['horse_num'] : '',
                    'horse_name' => isset($top['horse_name']) ? $top['horse_name'] : '',
                    'score' => isset($top['score']) ? $top['score'] : 0,
                    'role' => isset($top['role']) ? $top['role'] : '',
                    'decision' => isset($top['decision']) ? $top['decision'] : '',
                    'risk' => isset($top['risk']) ? $top['risk'] : 0,
                    'confidence' => isset($top['confidence']) ? $top['confidence'] : 0
                );
            }
        }

        usort($allTop, function($a, $b) {
            return $a['score'] < $b['score'] ? 1 : -1;
        });

        $bestBanker = isset($allTop[0]) ? $allTop[0] : array();
        $bestQ = array_slice($allTop, 0, 3);

        $coldCandidates = array();
        foreach ($byRace as $raceNum => $horses) {
            foreach ($horses as $horse) {
                if ($horse['rank'] >= 4 && $horse['score'] >= 50 && $horse['risk'] < 70) {
                    $horse['race_num'] = $raceNum;
                    $coldCandidates[] = $horse;
                }
            }
        }
        usort($coldCandidates, function($a, $b) {
            return $a['score'] < $b['score'] ? 1 : -1;
        });

        $avoid = array();
        foreach ($byRace as $raceNum => $horses) {
            foreach ($horses as $horse) {
                if ($horse['decision'] === 'SKIP' || $horse['risk'] >= 70) {
                    $horse['race_num'] = $raceNum;
                    $avoid[] = $horse;
                }
            }
        }
        usort($avoid, function($a, $b) {
            return $a['risk'] < $b['risk'] ? 1 : -1;
        });

        return array(
            'status' => 'OK',
            'presenter_version' => 'V46.0',
            'race_count' => count($races),
            'ranking_count' => count($ranking),
            'best_banker' => $bestBanker,
            'best_q' => $bestQ,
            'cold_candidates' => array_slice($coldCandidates, 0, 6),
            'avoid_candidates' => array_slice($avoid, 0, 6),
            'races' => $races
        );
    }
}
