<?php
declare(strict_types=1);

// Read-only diagnostic: compare the CLI DM driver's text encoding with the fixed C HTTP worker.
$mode = (string)($argv[1] ?? '');
if (!in_array($mode, ['--parent', '--child'], true)) {
    echo json_encode(['status' => 'default_deny', 'dml' => 0, 'http' => 0]), PHP_EOL;
    exit(78);
}
$pid = 112175;
if ($mode === '--parent') {
    $command = (string)file_get_contents('/proc/' . $pid . '/cmdline');
    if (strpos($command, '/tmp/zhct-dm-poc-20260928.fcpiiN/store/public') === false
        || strpos($command, '127.0.0.1:18080') === false) {
        throw new RuntimeException('C worker mismatch');
    }
    $environment = [];
    foreach (explode("\0", (string)file_get_contents('/proc/' . $pid . '/environ')) as $item) {
        $at = strpos($item, '=');
        if ($at !== false) $environment[substr($item, 0, $at)] = substr($item, $at + 1);
    }
    $svc = (string)($environment['DM_SVC_PATH'] ?? '');
    if (substr(hash('sha256', $svc), 0, 12) !== '5a92d26aec07'
        || !is_file($svc . '/dm_svc.conf')
        || strpos((string)file_get_contents($svc . '/dm_svc.conf'), 'CHAR_CODE=(PG_UTF8)') === false) {
        throw new RuntimeException('DM client profile mismatch');
    }
    $cmd = escapeshellarg('/www/server/php/73/bin/php')
        . ' -d display_errors=0 -d log_errors=0'
        . ' -d extension=/home/dmdba/dmdbms/drivers/php_pdo/php73_pdo_dm.so '
        . escapeshellarg(__FILE__) . ' --child';
    $process = proc_open($cmd, [1 => ['pipe', 'w'], 2 => ['pipe', 'w']],
        $pipes, null, $environment);
    if (!is_resource($process)) throw new RuntimeException('Child unavailable');
    $stdout = stream_get_contents($pipes[1]);
    $stderr = stream_get_contents($pipes[2]);
    fclose($pipes[1]);
    fclose($pipes[2]);
    $exit = proc_close($process);
    $result = json_decode((string)$stdout, true);
    if ($exit !== 0 || !is_array($result)) {
        echo json_encode(['status' => 'redacted_child_error',
            'exit' => $exit, 'stderr_class' => $stderr === '' ? 'none' : 'nonempty']), PHP_EOL;
        exit(2);
    }
    echo json_encode($result, JSON_UNESCAPED_SLASHES), PHP_EOL;
    exit(0);
}

if ((string)getenv('DM_SVC_PATH') === '' || (string)getenv('POC_PORT') !== '5237'
    || (string)getenv('POC_SCHEMA') !== 'ZHCT_APP') {
    throw new RuntimeException('Child target mismatch');
}
$pdo = new PDO('dm:host=127.0.0.1;port=5237;schema=ZHCT_APP',
    (string)getenv('POC_USER'), (string)getenv('POC_PASSWORD'),
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
if (strtoupper((string)$pdo->query('SELECT USER FROM DUAL')->fetchColumn()) !== 'ZHCT_APP') {
    throw new RuntimeException('Child identity mismatch');
}
$invalid = 0;
$responseHashMatches = 0;
$oldRawHashMatches = 0;
$count = 0;
foreach ($pdo->query('SELECT NAME FROM YDY_DEPARTMENT WHERE STATUS=1 AND IS_SHOW=1') as $row) {
    $name = is_resource($row['name']) ? stream_get_contents($row['name']) : (string)$row['name'];
    $count++;
    if (!mb_check_encoding($name, 'UTF-8')) $invalid++;
    $sha = substr(hash('sha256', $name), 0, 12);
    if ($sha === '21e4f26a7c46') $responseHashMatches++;
    if ($sha === '9a1011ca2076') $oldRawHashMatches++;
}
echo json_encode(['status' => 'read_only', 'rows' => $count,
    'invalid_utf8' => $invalid, 'http_name_hash_matches' => $responseHashMatches,
    'old_gbk_hash_matches' => $oldRawHashMatches,
    'dml' => 0, 'http' => 0], JSON_UNESCAPED_SLASHES), PHP_EOL;
