<?php

declare(strict_types=1);

$self = (string)hash_file('sha256', __FILE__);
if ((string)($argv[1] ?? '') !== '--execute'
    || (string)getenv('CDX_DMWF_APPROVE') !== 'ROOT_FRACTIONAL_WEIGHT_V1'
    || !hash_equals($self, (string)getenv('CDX_DMWF_SHA'))) {
    echo json_encode(['status'=>'default_deny','connected'=>false,'http_sent'=>false,'dml'=>false]), PHP_EOL;
    exit(78);
}
$root='/tmp/zhct-http-store-mysql.dQTTBP';$pid=10001;$base='http://127.0.0.1:18081';
if (hash_file('sha256',$root.'/application/p/controller/DateMenu.php')
        !=='792b56de2dc42d36e19fc1d0f852cd853dab8f7768c06276070d02a9bfc76013'
    || hash_file('sha256',$root.'/application/p/logic/DateMenu.php')
        !=='8035342ab42efa94eaaf832a89d8f5302451c3d6a5219d1b6e574b89791a4506') {
    throw new RuntimeException('Source drift');
}
$boundary=json_decode((string)file_get_contents($base.'/__poc_boundary'),true);
if(!is_array($boundary)||($boundary['external_stubs']??null)!==true
    ||($boundary['redis_isolated']??null)!==true||($boundary['real_queue']??true)!==false
    ||trim((string)file_get_contents('/proc/'.$pid.'/task/'.$pid.'/children'))!==''){
    throw new RuntimeException('HTTP boundary drift');
}
$config=require $root.'/application/database.php';$local=require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
foreach(['hostname','database','username','password']as$key)if(($config[$key]??null)!==($local[$key]??null))throw new RuntimeException('Not local MySQL');
$dsn='mysql:host='.$config['hostname'].';port='.(int)($config['hostport']??3306).';dbname='.$config['database'].';charset='.(string)$config['charset'];
$connect=static function()use($dsn,$config):PDO{return new PDO($dsn,$config['username'],$config['password'],[PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,PDO::ATTR_CASE=>PDO::CASE_LOWER]);};
$db=$connect();$identity=(string)$db->query("SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")->fetchColumn();
if(hash('sha256',$identity)!=='003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401')throw new RuntimeException('DB drift');
$sql="SELECT s.UUID,s.NAME,s.HEIGHT,s.WEIGHT,sd.DEPARTMENT_UUID FROM ydy_staff s"
    ." JOIN ydy_staff_department sd ON sd.STAFF_UUID=s.UUID JOIN ydy_department d ON d.UUID=sd.DEPARTMENT_UUID"
    ." WHERE s.IS_SHOW=1 AND d.IS_SHOW=1 AND ABS(s.WEIGHT-ROUND(s.WEIGHT))>0"
    ." AND s.UUID NOT LIKE 'CDX%' AND s.NAME NOT LIKE 'CDX%' ORDER BY s.ID LIMIT 1";
$source=$db->query($sql)->fetch(PDO::FETCH_ASSOC);if(!is_array($source))throw new RuntimeException('Fractional source absent');
$sourceSha=hash('sha256',serialize($source));$marker='CDXDMWF'.strtoupper(bin2hex(random_bytes(6)));$actorUuid=$marker.'U';$actorId=0;
try{$q=$db->prepare('INSERT INTO ydy_user (UUID,ACCOUNT,PWD,SALT,NAME,TYPE,STATUS,CREATE_TIME,CREATE_BY,IS_DELETE) VALUES (?,?,?,?,?,0,0,?,?,0)');
    $q->execute([$actorUuid,$marker,'DISABLED',strtoupper(bin2hex(random_bytes(8))),$marker,date('Y-m-d H:i:s'),$marker]);
    $q=$db->prepare('SELECT ID FROM ydy_user WHERE UUID=? AND ACCOUNT=? AND TYPE=0 AND CREATE_BY=?');$q->execute([$actorUuid,$marker,$marker]);$actorId=(int)$q->fetchColumn();if($actorId<=0)throw new RuntimeException('Actor absent');
    require_once $root.'/application/base/Security.php';$token=\app\base\Security::encrypt(implode("\t",[(string)$actorId,$actorUuid,$marker,'0','','',$marker]));
    $form=['date'=>'2001-01-01','department_uuid'=>(string)$source['department_uuid'],'staff_name'=>(string)$source['name'],'page'=>1,'page_size'=>200];
    $context=stream_context_create(['http'=>['method'=>'POST','timeout'=>20,'ignore_errors'=>true,
        'header'=>"Content-Type: application/x-www-form-urlencoded\r\ntoken: ".$token."\r\n",
        'content'=>http_build_query($form,'','&',PHP_QUERY_RFC3986)]]);
    $raw=file_get_contents($base.'/p/dateMenu/foodSurveyIndex',false,$context);$body=json_decode((string)$raw,true);$found=null;
    foreach(($body['data']['rows']??[])as$row)if(rtrim((string)($row['staff_uuid']??''))===rtrim((string)$source['uuid'])){$found=$row;break;}
    if((int)($body['code']??-1)!==0||!is_array($found)||(float)$found['weight']!==(float)$source['weight'])throw new RuntimeException('HTTP source mismatch');
    $after=$connect()->prepare('SELECT UUID,NAME,HEIGHT,WEIGHT,? DEPARTMENT_UUID FROM ydy_staff WHERE UUID=?');$after->execute([$source['department_uuid'],$source['uuid']]);
    if(hash('sha256',serialize($after->fetch(PDO::FETCH_ASSOC)))!==$sourceSha)throw new RuntimeException('Source changed');
    $result=['status'=>'tested-pass','source_height_type'=>gettype($source['height']),'source_height_value'=>$source['height'],
        'source_weight_type'=>gettype($source['weight']),'source_weight_value'=>$source['weight'],
        'response_height_type'=>gettype($found['height']??null),'response_height_value'=>$found['height']??null,
        'response_weight_type'=>gettype($found['weight']??null),'response_weight_value'=>$found['weight']??null];
}finally{if($actorId>0){$clean=$connect();$q=$clean->prepare('DELETE FROM ydy_user WHERE ID=? AND UUID=? AND ACCOUNT=? AND TYPE=0 AND CREATE_BY=?');$q->execute([$actorId,$actorUuid,$marker,$marker]);if($q->rowCount()!==1)throw new RuntimeException('Actor cleanup mismatch');
        $q=$connect()->prepare('SELECT COUNT(*) FROM ydy_user WHERE ID=? OR UUID=? OR ACCOUNT=?');$q->execute([$actorId,$actorUuid,$marker]);if((int)$q->fetchColumn()!==0)throw new RuntimeException('Actor remains');}}
echo json_encode($result,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES),PHP_EOL;
