<?php
declare(strict_types=1);

// Fixed-constant, SELECT-only SQL function compatibility probe.
$lane = (string)getenv('CDX_SQLFUNC_LANE');
if (!in_array($lane, ['B', 'C'], true)
    || count($argv) !== 2 || ($argv[1] ?? '') !== '--probe'
    || (string)getenv('CDX_SQLFUNC_APPROVE') !== 'FIXED_CONSTANT_SELECT_ONLY_V1'
    || !hash_equals((string)hash_file('sha256', __FILE__),
        (string)getenv('CDX_SQLFUNC_SHA'))) {
    echo json_encode(['status' => 'default_deny', 'connected' => false,
        'business_table_read' => false, 'dml' => false]), PHP_EOL;
    exit(78);
}
$stage = 'runtime';
set_exception_handler(static function (Throwable $error) use (&$stage): void {
    echo json_encode(['status' => 'redacted_stop', 'stage' => $stage,
        'error_class' => get_class($error), 'code' => (string)$error->getCode(),
        'dml' => false]), PHP_EOL;
    exit(2);
});
$targets = [
    'B' => ['/tmp/zhct-http-store-mysql.dQTTBP', 10001, 18081],
    'C' => ['/tmp/zhct-dm-poc-20260928.fcpiiN/store', 112175, 18080],
];
[$root, $pid, $port] = $targets[$lane];
if (PHP_VERSION_ID < 70300 || PHP_VERSION_ID >= 70400 || is_link($root)) {
    throw new RuntimeException('Runtime version or path drift');
}
$command = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
if (strpos($command, $root . '/public') === false
    || strpos($command, '127.0.0.1:' . $port) === false) {
    throw new RuntimeException('Isolated worker drift');
}
$runtime = require $root . '/application/database.php';
if (!is_array($runtime)) throw new RuntimeException('Runtime config missing');
if ($lane === 'B') {
    $config = $runtime;
    $local = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
    unset($config);
    foreach (['hostname', 'hostport', 'database', 'username', 'password', 'type'] as $key) {
        if (($runtime[$key] ?? null) !== ($local[$key] ?? null)) {
            throw new RuntimeException('Not code-local development MySQL');
        }
    }
    if ((string)$runtime['type'] !== 'mysql') throw new RuntimeException('Wrong B driver');
    $dsn = 'mysql:host=' . $runtime['hostname'] . ';port=' . (int)$runtime['hostport']
        . ';dbname=' . $runtime['database'] . ';charset=' . ($runtime['charset'] ?? 'utf8');
} else {
    foreach (['hostname' => 'POC_HOST', 'hostport' => 'POC_PORT',
        'database' => 'POC_SCHEMA', 'username' => 'POC_USER',
        'password' => 'POC_PASSWORD'] as $key => $env) {
        if ((string)($runtime[$key] ?? '') !== (string)getenv($env)) {
            throw new RuntimeException('C runtime/worker database drift');
        }
    }
    if ((string)getenv('POC_HOST') !== '127.0.0.1'
        || (string)getenv('POC_PORT') !== '5237'
        || strtoupper((string)getenv('POC_SCHEMA')) !== 'ZHCT_APP') {
        throw new RuntimeException('Not nonproduction Store DM');
    }
    $dsn = 'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';
}
$stage = 'connect_and_identity';
$db = new PDO($dsn, (string)$runtime['username'], (string)$runtime['password'], [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_CASE => PDO::CASE_LOWER,
    PDO::ATTR_TIMEOUT => 5,
]);
if ($lane === 'B') {
    $identity = (string)$db->query(
        "SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())")
        ->fetchColumn();
    if (hash('sha256', $identity)
        !== '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401') {
        throw new RuntimeException('B database identity drift');
    }
} else {
    $schema = strtoupper((string)$db->query(
        "SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn());
    if ($schema !== 'ZHCT_APP') throw new RuntimeException('C schema drift');
}
$queries = [
    'date_format' => "SELECT DATE_FORMAT(CAST('2026-02-03 14:05:06' AS DATETIME), '%Y-%m-%d') AS V",
    'field' => "SELECT FIELD('b','a','b','c') AS V",
    'find_in_set' => "SELECT FIND_IN_SET('b','a,b,c') AS V",
    'ifnull' => 'SELECT IFNULL(NULL,7) AS V',
    'group_concat_order' => "SELECT GROUP_CONCAT(X ORDER BY X ASC) AS V"
        . " FROM (SELECT 'b' X UNION ALL SELECT 'a' X) T",
    'year' => "SELECT YEAR(CAST('2026-02-03' AS DATE)) AS V",
];
$results = [];
foreach ($queries as $name => $sql) {
    $stage = 'select_' . $name;
    try {
        $value = $db->query($sql)->fetchColumn();
        $results[$name] = ['ok' => true, 'value' => is_scalar($value) ? (string)$value : null,
            'php_type' => gettype($value)];
    } catch (PDOException $error) {
        $results[$name] = ['ok' => false,
            'sqlstate' => (string)($error->errorInfo[0] ?? ''),
            'native_code' => (string)($error->errorInfo[1] ?? '')];
    }
}
echo json_encode(['status' => 'fixed_constant_select_complete',
    'lane' => $lane, 'results' => $results,
    'business_table_read' => false, 'http_sent' => false, 'dml' => false],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
