<?php

declare(strict_types=1);

// Fresh one-shot code-local MySQL handshake and SELECT 1. No business table.
if ($argc!==2 || $argv[1]!=='--one-shot-local-select1') {
    fwrite(STDERR,"Explicit one-shot read-only health flag required\n");
    exit(2);
}
$phase='a-runtime';
try {
    $root='/tmp/zhct-http-store-a.l5omH8';
    $cmd=str_replace("\0",' ',(string)file_get_contents('/proc/21023/cmdline'));
    if (strpos($cmd,' -S 127.0.0.1:18097 ')===false
        || strpos($cmd,$root.'/public')===false
        || substr_count($cmd,' -S ')!==1) {
        throw new RuntimeException('A isolated PID changed');
    }
    $body=@file_get_contents('http://127.0.0.1:18097/__poc_boundary',
        false,stream_context_create(['http'=>[
            'timeout'=>3,'ignore_errors'=>true,
        ]]));
    $headers=$http_response_header??[];
    $status=preg_match('/^HTTP\/\S+\s+(\d+)/',
        (string)($headers[0]??''),$match)?(int)$match[1]:0;
    $boundary=json_decode((string)$body,true);
    if ($status!==200 || !is_array($boundary)
        || empty($boundary['external_stubs'])
        || empty($boundary['redis_isolated'])
        || !empty($boundary['real_queue'])) {
        throw new RuntimeException('A HTTP boundary unavailable');
    }
    $phase='code-local-config';
    $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('A runtime not code-local development MySQL');
        }
    }
    if (($runtime['type']??null)!=='mysql'
        || (int)($runtime['hostport']??3306)
            !==(int)($local['hostport']??3306)) {
        throw new RuntimeException('Wrong A MySQL dialect/port');
    }
    $phase='new-pdo-handshake';
    $start=microtime(true);
    $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,
        ]);
    $phase='select1';
    $value=(int)$db->query('SELECT 1')->fetchColumn();
    $version=(string)$db->query('SELECT VERSION()')->fetchColumn();
    echo json_encode([
        'status'=>$value===1 && strpos($version,'5.6.')===0?'healthy':'unexpected',
        'a_pid_fixed'=>true,'a_boundary_http200'=>true,
        'mysql_5_6'=>strpos($version,'5.6.')===0,
        'select1'=>$value,
        'elapsed_ms'=>(int)round((microtime(true)-$start)*1000),
    ],JSON_UNESCAPED_SLASHES).PHP_EOL;
    if ($value!==1 || strpos($version,'5.6.')!==0) exit(1);
} catch (Throwable $error) {
    echo json_encode(['status'=>'blocked','phase'=>$phase,
        'class'=>get_class($error),
        'code'=>(string)$error->getCode()],JSON_UNESCAPED_SLASHES).PHP_EOL;
    exit(1);
}
