<?php
/**
 * Chairman Analysis Adapter v1.5
 * Safe production adapter for future analysis.php integration.
 * Never throws fatal error to caller; logs and returns empty fallback.
 */
class ChairmanAnalysisAdapter {
    private $chairman;
    private $config;
    private $lastDebug = array();

    public function __construct($chairman, array $config=array()) {
        $this->chairman = $chairman;
        $this->config = $config;
    }

    private function logDir() {
        $dir = isset($this->config['log_dir']) ? $this->config['log_dir'] : dirname(__DIR__) . '/logs';
        if(!is_dir($dir)) @mkdir($dir, 0775, true);
        return $dir;
    }

    private function log($file, $message) {
        $line = '['.date('Y-m-d H:i:s').'] '.$message.PHP_EOL;
        @file_put_contents($this->logDir().'/'.$file, $line, FILE_APPEND);
    }

    private function startDebug($name) {
        return array(
            'name'=>$name,
            'start'=>microtime(true),
            'memory_start'=>memory_get_usage(true)
        );
    }

    private function endDebug($ctx, $extra=array()) {
        $ctx['end'] = microtime(true);
        $ctx['elapsed_ms'] = round(($ctx['end']-$ctx['start'])*1000, 3);
        $ctx['memory_end'] = memory_get_usage(true);
        $ctx['memory_delta'] = $ctx['memory_end'] - $ctx['memory_start'];
        foreach($extra as $k=>$v){ $ctx[$k]=$v; }
        $this->lastDebug = $ctx;
        return $ctx;
    }

    public function debug() {
        return $this->lastDebug;
    }

    public function health() {
        try {
            return $this->chairman->health();
        } catch (Throwable $e) {
            $this->log('error.log','health error: '.$e->getMessage());
            return array('status'=>'ERROR','message'=>$e->getMessage());
        } catch (Exception $e) {
            $this->log('error.log','health error: '.$e->getMessage());
            return array('status'=>'ERROR','message'=>$e->getMessage());
        }
    }

    public function summary($raceDate, $venue='', $raceNum=0) {
        $ctx=$this->startDebug('summary');
        try {
            $rows = $this->chairman->getRaceSummary($raceDate,$venue,$raceNum);
            $this->endDebug($ctx,array('rows'=>count($rows)));
            return is_array($rows) ? $rows : array();
        } catch (Throwable $e) {
            $this->log('error.log','summary error: '.$e->getMessage());
            $this->endDebug($ctx,array('error'=>$e->getMessage()));
            return array();
        } catch (Exception $e) {
            $this->log('error.log','summary error: '.$e->getMessage());
            $this->endDebug($ctx,array('error'=>$e->getMessage()));
            return array();
        }
    }

    public function ranking($raceDate, $venue='', $raceNum=0) {
        $ctx=$this->startDebug('ranking');
        try {
            $rows = $this->chairman->getRaceRanking($raceDate,$venue,$raceNum);
            $this->endDebug($ctx,array('rows'=>count($rows)));
            return is_array($rows) ? $rows : array();
        } catch (Throwable $e) {
            $this->log('error.log','ranking error: '.$e->getMessage());
            $this->endDebug($ctx,array('error'=>$e->getMessage()));
            return array();
        } catch (Exception $e) {
            $this->log('error.log','ranking error: '.$e->getMessage());
            $this->endDebug($ctx,array('error'=>$e->getMessage()));
            return array();
        }
    }

    public function top($raceDate, $venue='', $raceNum=0) {
        $ranking = $this->ranking($raceDate,$venue,$raceNum);
        return count($ranking) ? $ranking[0] : null;
    }

    public function payload($raceDate, $venue='', $raceNum=0) {
        $ctx=$this->startDebug('payload');
        try {
            $payload = $this->chairman->getAnalysisPayload($raceDate,$venue,$raceNum);
            if(!is_array($payload)) $payload = array();
            $this->endDebug($ctx,array(
                'summary'=>isset($payload['summary']) && is_array($payload['summary']) ? count($payload['summary']) : 0,
                'ranking'=>isset($payload['ranking']) && is_array($payload['ranking']) ? count($payload['ranking']) : 0
            ));
            return $payload;
        } catch (Throwable $e) {
            $this->log('error.log','payload error: '.$e->getMessage());
            $this->endDebug($ctx,array('error'=>$e->getMessage()));
            return array('summary'=>array(),'ranking'=>array(),'error'=>$e->getMessage());
        } catch (Exception $e) {
            $this->log('error.log','payload error: '.$e->getMessage());
            $this->endDebug($ctx,array('error'=>$e->getMessage()));
            return array('summary'=>array(),'ranking'=>array(),'error'=>$e->getMessage());
        }
    }
}
