<?php
/**
 * Inspection-only guard for wr_ai_decision / wr_ai_engine_vote.
 * Never alters schema.
 */
class ChairmanSchemaCompatibilityGuardV501 {
    private $db;
    public function __construct(mysqli $db) { $this->db=$db; }

    private function tableExists($table) {
        $tableEsc=$this->db->real_escape_string($table);
        $rs=@$this->db->query("SHOW TABLES LIKE '{$tableEsc}'");
        return $rs && $rs->num_rows>0;
    }

    private function columns($table) {
        $out=array();
        if (!$this->tableExists($table)) return $out;
        $rs=@$this->db->query("SHOW COLUMNS FROM `".$this->db->real_escape_string($table)."`");
        if ($rs) while($r=$rs->fetch_assoc()) $out[]=$r['Field'];
        return $out;
    }

    public function inspect() {
        $decision=$this->columns('wr_ai_decision');
        $vote=$this->columns('wr_ai_engine_vote');

        $legacyDecision=array('main_pick','cover_pick','confidence','gate_score','expected_hit_rate');
        $brainV2Decision=array('horse_a','horse_b','final_confidence','committee_score','chairman_score','brain_version');
        $legacyVote=array('engine_name','vote_weight','engine_success_rate','meta_json');
        $brainV2Vote=array('engine_code','engine_weight_used','weighted_score','detail_json');

        $has=function($cols,$required){ return count(array_intersect($required,$cols))===count($required); };

        $decisionProfile='UNKNOWN';
        if (!$decision) $decisionProfile='MISSING';
        elseif ($has($decision,$brainV2Decision)) $decisionProfile='BRAIN_V2';
        elseif ($has($decision,$legacyDecision)) $decisionProfile='LEGACY_V17';
        elseif (in_array('horse_a',$decision,true) && in_array('main_pick',$decision,true)) $decisionProfile='HYBRID';
        else $decisionProfile='CUSTOM';

        $voteProfile='UNKNOWN';
        if (!$vote) $voteProfile='MISSING';
        elseif ($has($vote,$brainV2Vote)) $voteProfile='BRAIN_V2';
        elseif ($has($vote,$legacyVote)) $voteProfile='LEGACY_V17';
        elseif (in_array('engine_code',$vote,true) && in_array('engine_name',$vote,true)) $voteProfile='HYBRID';
        else $voteProfile='CUSTOM';

        $issues=array();
        if ($decisionProfile==='MISSING') $issues[]='wr_ai_decision table missing';
        if ($voteProfile==='MISSING') $issues[]='wr_ai_engine_vote table missing';
        if (in_array($decisionProfile,array('CUSTOM','HYBRID'),true)) $issues[]='wr_ai_decision schema needs explicit adapter';
        if (in_array($voteProfile,array('CUSTOM','HYBRID'),true)) $issues[]='wr_ai_engine_vote schema needs explicit adapter';

        return array(
            'status'=>empty($issues)?'OK':'WARNING',
            'decision_profile'=>$decisionProfile,
            'vote_profile'=>$voteProfile,
            'decision_columns'=>$decision,
            'vote_columns'=>$vote,
            'issues'=>$issues,
            'safe_mode'=>'INSPECTION_ONLY',
            'alter_executed'=>false
        );
    }
}
