<?php
/**
 * Chairman Production Core v3.1
 * One stable entry point for analysis.php integration.
 */
class ChairmanProductionCore {
    private $v44Engine;
    private $repo;

    public function __construct(V44RankingOptimizerEngine $v44Engine, V44ProductionRepository $repo) {
        $this->v44Engine = $v44Engine;
        $this->repo = $repo;
    }

    private function rows($sql) {
        return $this->repo->rows($sql);
    }

    private function q($s) {
        return $this->repo->q($s);
    }

    public function latestOutput($raceDate, $venue='', $raceNum=0) {
        $where = array("race_date=".$this->q($raceDate));
        if($venue !== '') $where[] = "venue=".$this->q($venue);
        if((int)$raceNum > 0) $where[] = "race_num=".(int)$raceNum;

        $ranking = array();
        if($this->repo->tableExists('wr_chairman_production_score_v44')){
            $ranking = $this->rows("SELECT * FROM wr_chairman_production_score_v44 WHERE ".implode(' AND ',$where)." ORDER BY race_num ASC, race_rank ASC, calibrated_score DESC");
        }

        $summary = array();
        if($this->repo->tableExists('wr_chairman_race_optimizer_v44')){
            $summary = $this->rows("SELECT * FROM wr_chairman_race_optimizer_v44 WHERE ".implode(' AND ',$where)." ORDER BY race_num ASC");
        }

        return array($summary,$ranking);
    }

    public function buildIfNeeded($raceDate, $venue='', $raceNum=0, $mode='BALANCED') {
        list($summary,$ranking) = $this->latestOutput($raceDate,$venue,$raceNum);
        if(count($ranking) > 0) {
            return array(
                'used_cache' => true,
                'build_status' => 'SKIPPED_EXISTING_OUTPUT',
                'summary_rows' => count($summary),
                'ranking_rows' => count($ranking)
            );
        }

        $result = $this->v44Engine->build($raceDate,$venue,$raceNum,$mode);
        return array(
            'used_cache' => false,
            'build_status' => 'BUILT',
            'build_result' => $result
        );
    }

    public function payload($raceDate, $venue='', $raceNum=0, $mode='BALANCED', $autoBuild=true) {
        $build = array('auto_build'=>false);
        if($autoBuild) {
            $build = $this->buildIfNeeded($raceDate,$venue,$raceNum,$mode);
        }

        list($summary,$ranking) = $this->latestOutput($raceDate,$venue,$raceNum);

        $topByRace = array();
        foreach($ranking as $r) {
            $rn = (string)$r['race_num'];
            if(!isset($topByRace[$rn])) {
                $topByRace[$rn] = array(
                    'race_num' => (int)$r['race_num'],
                    'top_horse' => $r['horse_num'],
                    'top_name' => $r['horse_name'],
                    'top_score' => (float)$r['calibrated_score'],
                    'role' => $r['role_tag'],
                    'decision' => $r['final_decision']
                );
            }
        }

        return array(
            'status' => 'OK',
            'core_version' => '3.1',
            'source_engine' => 'V44RankingOptimizerEngine',
            'race_date' => $raceDate,
            'venue' => $venue,
            'race_num' => (int)$raceNum,
            'auto_build' => $build,
            'counts' => array(
                'summary' => count($summary),
                'ranking' => count($ranking),
                'top_by_race' => count($topByRace)
            ),
            'top_by_race' => array_values($topByRace),
            'summary' => $summary,
            'ranking' => $ranking,
            'generated_at' => date('c')
        );
    }

    public function buildCache($raceDate, $venue='', $raceNum=0, $mode='BALANCED') {
        $payload = $this->payload($raceDate,$venue,$raceNum,$mode,true);
        $cacheDir = dirname(__DIR__) . '/cache';
        if(!is_dir($cacheDir)) @mkdir($cacheDir,0775,true);
        $safeVenue = preg_replace('/[^a-zA-Z0-9_\-]/','_', (string)$venue);
        $file = $cacheDir . '/production_core_' . $raceDate . ($safeVenue!==''?'_'.$safeVenue:'') . ((int)$raceNum>0?'_R'.(int)$raceNum:'') . '.json';
        file_put_contents($file, json_encode($payload, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
        return array('status'=>'OK','file'=>$file,'bytes'=>file_exists($file)?filesize($file):0,'payload'=>$payload);
    }
}
