<?php

declare(strict_types=1);

// A/B read-only zero-row ThinkORM probe. No records, SQL text or bind values emitted.
set_exception_handler(static function (Throwable $error): void {
    fwrite(STDERR, 'N3_AB_ZERO_ROW_FAILED ' . get_class($error) . PHP_EOL);
    exit(2);
});
$variant = (string)getenv('POC_VARIANT');
$runtimes = [
    'A' => ['/tmp/zhct-http-ai-macos.zjaU8h', 'http://127.0.0.1:18105', 13109],
    'B' => ['/tmp/zhct-http-ai-macos.x2CCZX', 'http://127.0.0.1:18101', 13127],
];
if (!isset($runtimes[$variant])) throw new RuntimeException('Only isolated A/B allowed');
[$root, $base, $pid] = $runtimes[$variant];
$localPath = '/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local';
if (realpath((string)getenv('POC_MYSQL_LOCAL_ENV')) !== realpath($localPath)) {
    throw new RuntimeException('Only code local DB allowed');
}
$local = parse_ini_file($localPath, true, INI_SCANNER_RAW);
if (!is_array($local) || !isset($local['DATABASE'], $local['DATABASE_ZHCT'])) {
    throw new RuntimeException('Code local two-business-DB config absent');
}
$port = $variant === 'A' ? 18105 : 18101;
if (trim((string)shell_exec('lsof -nP -iTCP:' . $port . ' -sTCP:LISTEN -t 2>/dev/null')) !== (string)$pid) {
    throw new RuntimeException('A/B listener changed');
}
$process = (string)shell_exec('ps eww -p ' . $pid . ' -o command=');
if (strpos($process, $root . '/public') === false
    || strpos($process, 'php -S 127.0.0.1:' . $port) === false) {
    throw new RuntimeException('A/B process identity mismatch');
}
$env = [];
$expected = ['POC_TARGET_ROOT' => $root, 'POC_BASE_URL' => $base,
    'POC_DIALECT' => 'mysql'];
foreach (['DATABASE' => 'POC_AI_', 'DATABASE_ZHCT' => 'POC_'] as $section => $prefix) {
    foreach (['HOSTNAME' => 'HOST', 'HOSTPORT' => 'PORT',
        'DATABASE' => 'SCHEMA', 'USERNAME' => 'USER',
        'PASSWORD' => 'PASSWORD'] as $from => $to) {
        $expected[$prefix . $to] = (string)$local[$section][$from];
    }
}
foreach ($expected as $key => $value) {
    $pattern = '/(?:^|\s)' . preg_quote($key, '/') . '=([^\s]*)/';
    if (!preg_match($pattern, $process, $match) || $match[1] !== $value) {
        throw new RuntimeException('A/B HTTP DB differs from code local');
    }
    $env[$key] = $match[1];
}
foreach (['POC_TARGET_ROOT', 'POC_BASE_URL', 'POC_DIALECT',
    'POC_AI_HOST', 'POC_AI_PORT', 'POC_AI_SCHEMA', 'POC_AI_USER',
    'POC_AI_PASSWORD', 'POC_HOST', 'POC_PORT', 'POC_SCHEMA', 'POC_USER',
    'POC_PASSWORD'] as $key) {
    if (empty($env[$key])) throw new RuntimeException('C test process context missing');
    putenv($key . '=' . $env[$key]);
}
define('TP_ENV', 'poc');
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
require $root . '/vendor/autoload.php';
(new \think\App($root))->setEnvName('poc')->initialize();
$conditions = [
    'old' => ['staff_id' => 0, 'is_delete' => 0,
        'set_date' => ['between', '2026-10-02', '2026-10-02']],
    'new' => [['staff_id', '=', 0], ['is_delete', '=', 0],
        ['set_date', 'between', ['2026-10-02', '2026-10-02']]],
];
$result = [];
foreach ($conditions as $name => $where) {
    try {
        $query = \think\facade\Db::connect()->name('staff_weight')
            ->whereRaw('1=0')->where($where)->field('id');
        $sql = (string)(clone $query)->fetchSql(true)->select();
        $result[$name] = [
            'set_date_in' => preg_match('/set_date[^a-z0-9]+IN\\s*\\(/i', $sql) === 1,
            'set_date_between' => preg_match('/set_date[^a-z0-9]+BETWEEN\\b/i', $sql) === 1,
        ];
        $rows = $query->select();
        $result[$name]['zero_rows'] = $rows->isEmpty();
        $result[$name]['query_success'] = true;
    } catch (Throwable $error) {
        $detail = method_exists($error, 'getData') ? (array)$error->getData() : [];
        $pdo = (array)($detail['PDO Error Info'] ?? []);
        $result[$name]['query_success'] = false;
        $result[$name]['class'] = get_class($error);
        $result[$name]['sqlstate'] = (string)($pdo['SQLSTATE'] ?? '');
        $result[$name]['driver_code'] = (string)($pdo['Driver Error Code'] ?? '');
    }
}
echo json_encode(['mode' => $variant . '-read-only-zero-row-query',
    'result' => $result],
    JSON_UNESCAPED_SLASHES) . PHP_EOL;
