<?php
require_once dirname(__DIR__, 2) . '/runtime/wr_bootstrap.php';
@set_time_limit(1200); @ini_set('memory_limit', '1536M');
require_once dirname(__DIR__, 2) . '/config/config.php';
if (!wr_db_guard_normalize()) {
    wr_json_response(array('message'=>'DB connection unavailable'),'V65','65.0.0','ERROR',500,'',false);
}
require_once dirname(__DIR__) . '/memory/ChairmanPatternMemoryEngineV53.php';
require_once dirname(__DIR__) . '/runtime/wr_chairman_os_scheduler_v60_0.php';
require_once dirname(__DIR__) . '/audit/wr_chairman_pre_race_leakage_auditor_v61_0.php';
require_once dirname(__DIR__) . '/audit/wr_chairman_production_readiness_gate_v62_0.php';
require_once dirname(__DIR__) . '/audit/wr_chairman_shadow_run_validator_v63_0.php';
require_once dirname(__DIR__) . '/audit/wr_chairman_go_live_rehearsal_v64_0.php';
require_once dirname(__DIR__) . '/audit/wr_chairman_final_release_certifier_v65_0.php';

function v65_api_date(){
    foreach(array('race_date','date','review_date') as $key){
        if(!isset($_GET[$key])) continue;
        $candidate=trim((string)$_GET[$key]);
        $dt=DateTimeImmutable::createFromFormat('!Y-m-d',$candidate);
        $errors=DateTimeImmutable::getLastErrors();
        if($dt instanceof DateTimeImmutable && ($errors===false || ((int)$errors['warning_count']===0 && (int)$errors['error_count']===0)) && $dt->format('Y-m-d')===$candidate) return $candidate;
    }
    return (new DateTimeImmutable('now',new DateTimeZone('Asia/Hong_Kong')))->format('Y-m-d');
}
$date=v65_api_date();
$venue=isset($_GET['venue'])?preg_replace('/[^A-Za-z0-9_\-]/','',trim((string)$_GET['venue'])):'';
$action=isset($_GET['action'])?trim((string)$_GET['action']):'latest';
$sourceEngine=new ChairmanPatternMemoryEngineV53($conn);
$source=$action==='build'?$sourceEngine->build($date,$venue):$sourceEngine->latest($date,$venue);
if(!is_array($source)) $source=array();
$os=(new ChairmanOSSchedulerV60())->build($source,$date,$venue);
$leakage=(new ChairmanPreRaceLeakageAuditorV61())->audit($source,$date,$venue);
$readiness=(new ChairmanProductionReadinessGateV62())->certify($source,$os,$leakage,$date,$venue);
$shadow=(new ChairmanShadowRunValidatorV63())->validate($source,$readiness,$date,$venue);
$rehearsal=(new ChairmanGoLiveRehearsalV64())->rehearse($source,$os,$leakage,$readiness,$shadow,$date,$venue);
$result=(new ChairmanFinalReleaseCertifierV65())->certify($source,$os,$leakage,$readiness,$shadow,$rehearsal,$date,$venue);
$result['source_v53_status']=isset($source['status'])?$source['status']:'EMPTY';
$result['v64_rehearsal_summary']=isset($rehearsal['rehearsal_summary'])?$rehearsal['rehearsal_summary']:array();
$result['v63_shadow_summary']=isset($shadow['shadow_summary'])?$shadow['shadow_summary']:array();
$result['v62_readiness_summary']=isset($readiness['readiness_summary'])?$readiness['readiness_summary']:array();
$result['v61_leakage_summary']=isset($leakage['leakage_summary'])?$leakage['leakage_summary']:array();
$result['v60_os_summary']=isset($os['os_summary'])?$os['os_summary']:array();
$status=isset($result['release_summary']['production_gate']) && $result['release_summary']['production_gate']==='PRODUCTION_GO_LIVE'?'OK':'BLOCKED';
wr_json_response($result,'V65','65.0.0',$status,200,$date.'|'.$venue,true);
