<?php

declare(strict_types=1);

// Synthetic constants only. Tests the copied guard against each effective PDO.
if ($argc!==2 || !in_array($argv[1],
    ['--probe-b-mysql','--probe-c-dm'],true)) {
    fwrite(STDERR,"Explicit B/C synthetic read-only probe required\n");
    exit(2);
}
$lane=$argv[1]==='--probe-b-mysql'?'B':'C';
try {
    if ($lane==='B') {
        $root='/tmp/zhct-http-store-mysql.dQTTBP';
        $load=static function(string $path): array { return require $path; };
        $local=$load('/workspace/zhct/zhctproject/store/application/config/local/database.php');
        $runtime=$load($root.'/application/database.php');
        foreach (['hostname','database','username','password'] as $key) {
            if (!isset($local[$key],$runtime[$key])
                || $local[$key]!==$runtime[$key]) {
                throw new RuntimeException('Wrong code-local MySQL');
            }
        }
        $db=new PDO('mysql:host='.$local['hostname'].';port='.
            (int)($local['hostport']??3306).';dbname='.$local['database']
            .';charset=utf8mb4',(string)$local['username'],
            (string)$local['password'],[
                PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_EMULATE_PREPARES=>false,
                PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,
                PDO::ATTR_TIMEOUT=>8,
            ]);
        if (strpos((string)$db->query('SELECT VERSION()')->fetchColumn(),'5.6.')===false) {
            throw new RuntimeException('Wrong MySQL version');
        }
        $sql='SELECT CAST(0.00 AS DECIMAL(5,2)) Z,'
            .' CAST(12.30 AS DECIMAL(5,2)) P';
    } else {
        $root='/tmp/zhct-dm-poc-20260928.fcpiiN/store';
        $pid=(string)getenv('POC_RUNTIME_PID');
        if ($pid!=='112175' || strpos((string)file_get_contents(
            '/proc/'.$pid.'/cmdline'),$root.'/public')===false) {
            throw new RuntimeException('Wrong isolated C PID');
        }
        $env=array_fill_keys(['POC_HOST','POC_PORT','POC_SCHEMA',
            'POC_USER','POC_PASSWORD'],'');
        foreach (explode("\0",(string)file_get_contents('/proc/'.$pid.'/environ')) as $entry) {
            $parts=explode('=',$entry,2);
            if (count($parts)===2 && array_key_exists($parts[0],$env)) {
                $env[$parts[0]]=$parts[1];
            }
        }
        if ($env['POC_HOST']!=='127.0.0.1' || $env['POC_PORT']!=='5237'
            || strtoupper($env['POC_SCHEMA'])!=='ZHCT_APP'
            || strtoupper($env['POC_USER'])!=='ZHCT_APP'
            || $env['POC_PASSWORD']==='') {
            throw new RuntimeException('Wrong nonproduction C DB');
        }
        $db=new PDO('dm:host=127.0.0.1;port=5237;schema=ZHCT_APP',
            $env['POC_USER'],$env['POC_PASSWORD'],[
                PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,
            ]);
        if (strtoupper((string)$db->query(
            "SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")
            ->fetchColumn())!=='ZHCT_APP') {
            throw new RuntimeException('Wrong C schema');
        }
        $sql='SELECT CAST(0.00 AS DECIMAL(5,2)) Z,'
            .' CAST(12.30 AS DECIMAL(5,2)) P FROM DUAL';
    }
    $guard=$root.'/application/common/service/NutritionWeightGuard.php';
    if ((string)hash_file('sha256',$guard)!==
        '24900e393a8d4e2d0bc1bb71b14c97d553054967ad6015a89b4643ceff4b94c7') {
        throw new RuntimeException('Unexpected guard source');
    }
    require_once $guard;
    $row=$db->query($sql)->fetch(PDO::FETCH_ASSOC);
    $row=array_change_key_case((array)$row,CASE_LOWER);
    $zero=$row['z']??null;
    $positive=$row['p']??null;
    $guardClass=\app\common\service\NutritionWeightGuard::class;
    $result=[
        'lane'=>$lane,'source'=>'synthetic-constant-select',
        'zero_php_type'=>gettype($zero),
        'positive_php_type'=>gettype($positive),
        'zero_division_allowed'=>$guardClass::canDivide($zero),
        'positive_division_allowed'=>$guardClass::canDivide($positive),
        'zero_string_allowed'=>$guardClass::canDivide('0.00'),
        'positive_string_allowed'=>$guardClass::canDivide('12.30'),
    ];
    echo json_encode($result,JSON_UNESCAPED_SLASHES).PHP_EOL;
    if ($result['zero_division_allowed']
        || !$result['positive_division_allowed']
        || $result['zero_string_allowed']
        || !$result['positive_string_allowed']) exit(1);
} catch (Throwable $error) {
    echo json_encode(['status'=>'blocked','lane'=>$lane,
        'class'=>get_class($error),
        'code'=>(string)$error->getCode()],JSON_UNESCAPED_SLASHES).PHP_EOL;
    exit(1);
}
