<?php
declare(strict_types=1);

$lane = (string)($argv[1] ?? '');
if (!in_array($lane, ['B', 'C'], true)) {
    fwrite(STDERR, "DENIED business_http=0 business_dml=0\n"); exit(78);
}
if ($lane === 'B') {
    $config = include '/tmp/zhct-http-store-mysql.dQTTBP/application/config/local/database.php';
    if (!is_array($config) || ($config['database'] ?? '') !== 'zhct'
        || hash('sha256', (string)($config['hostname'] ?? ''))
            !== '47e8be48b0cfd56dcdb9d9d426e6637b245f340b4efad4cd2f084ec5851ecc8e') {
        throw new RuntimeException('B code-local MySQL identity drift');
    }
    $db = new PDO('mysql:host=' . $config['hostname'] . ';port=3306;dbname=zhct;charset=utf8',
        $config['username'], $config['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
    $port = 18081;
} else {
    if (getenv('POC_DIALECT') !== 'dm' || getenv('POC_HOST') !== '127.0.0.1'
        || getenv('POC_PORT') !== '5237' || getenv('POC_SCHEMA') !== 'ZHCT_APP'
        || getenv('POC_USER') !== 'ZHCT_APP') {
        throw new RuntimeException('C isolated Store DM identity drift');
    }
    $db = new PDO('dm:host=127.0.0.1;port=5237;schema=ZHCT_APP',
        getenv('POC_USER'), getenv('POC_PASSWORD'),
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
    if ($db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn() !== 'ZHCT_APP') {
        throw new RuntimeException('C schema drift');
    }
    $port = 18080;
}
$visibleCount = (int)$db->query('SELECT COUNT(*) FROM ydy_staff WHERE is_show=1')->fetchColumn();
$staffRows = $db->query('SELECT id,uuid,name,sex FROM ydy_staff'
    . ' WHERE is_show=1 ORDER BY id DESC'
    . ($lane === 'B' ? ' LIMIT 300' : ' FETCH FIRST 300 ROWS ONLY'))
    ->fetchAll(PDO::FETCH_ASSOC);
if (!$staffRows) throw new RuntimeException('no visible staff source');
$hardware = $db->prepare('SELECT COUNT(*) FROM ydy_hardware_img'
    . ' WHERE staff_uuid=? AND is_del=0');
$department = $db->prepare('SELECT COUNT(*) FROM ydy_staff_department sd'
    . ' JOIN ydy_department d ON sd.department_uuid=d.uuid WHERE sd.staff_uuid=?');
$candidate = null;
foreach ($staffRows as $offset => $row) {
    if ($offset >= 300) break;
    $row = array_change_key_case($row, CASE_LOWER);
    $hardware->execute([(string)$row['uuid']]);
    $noImage = (int)$hardware->fetchColumn() === 0;
    $department->execute([(string)$row['uuid']]);
    $hasDepartment = (int)$department->fetchColumn() > 0;
    if ($noImage && $hasDepartment) {
        $candidate = ['row' => $row, 'page' => $offset + 1];
        break;
    }
}
if ($candidate === null) throw new RuntimeException('no safe no-image staff in first 300');
$http = static function (string $path, array $form) use ($port): array {
    $ctx = stream_context_create(['http' => [
        'method' => 'POST', 'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query($form, '', '&', PHP_QUERY_RFC3986),
        'ignore_errors' => true, 'timeout' => 18, 'follow_location' => 0,
    ]]);
    $handle = @fopen('http://127.0.0.1:' . $port . $path, 'rb', false, $ctx);
    if (!is_resource($handle)) throw new RuntimeException('isolated Staff HTTP unavailable');
    $raw = stream_get_contents($handle, 2097153);
    fclose($handle);
    if (!is_string($raw) || strlen($raw) > 2097152) throw new RuntimeException('staff response cap');
    $body = json_decode($raw, true);
    if (!is_array($body)) throw new RuntimeException('Staff HTTP non-JSON');
    return $body;
};
$form = ['page' => $candidate['page'], 'page_size' => 1];
$list = $http('/p/api/getStaffList', $form);
$wrapped = $http('/p/api/getStaffLists', $form);
$detail = $http('/p/api/getStaff', ['staff_uuid' => $candidate['row']['uuid']]);
$listData = $list['data'] ?? null;
$wrappedData = $wrapped['data']['data'] ?? null;
$sourceStaff = $candidate['row'];
if (!is_array($listData) || count($listData) !== 1
    || !is_array($wrappedData) || $wrappedData !== $listData
    || (int)($wrapped['code'] ?? -1) !== 0
    || (int)($list['total'] ?? -1) !== $visibleCount
    || (int)($wrapped['data']['total'] ?? -1) !== $visibleCount
    || (string)($listData[0]['uuid'] ?? '') !== (string)$sourceStaff['uuid']
    || (string)($listData[0]['name'] ?? '') !== (string)$sourceStaff['name']
    || !is_array($detail)
    || (string)($detail['uuid'] ?? '') !== (string)$sourceStaff['uuid']
    || (string)($detail['name'] ?? '') !== (string)$sourceStaff['name']) {
    throw new RuntimeException('Staff HTTP differs from original safe staff row');
}
$departmentRows = $db->prepare('SELECT d.uuid,d.name FROM ydy_staff_department sd'
    . ' JOIN ydy_department d ON sd.department_uuid=d.uuid WHERE sd.staff_uuid=?');
$departmentRows->execute([(string)$sourceStaff['uuid']]);
$sourceDepartments = array_map(static function (array $row): array {
    return array_change_key_case($row, CASE_LOWER);
}, $departmentRows->fetchAll(PDO::FETCH_ASSOC));
foreach ([$listData[0], $detail] as $item) {
    $match = false;
    foreach ($sourceDepartments as $sourceDepartment) {
        if ((string)($item['department_uuid'] ?? '') === (string)$sourceDepartment['uuid']
            && (string)($item['department_name'] ?? '') === (string)$sourceDepartment['name']) {
            $match = true;
            break;
        }
    }
    if (!$match || (string)($item['head_img'] ?? '') !== '') {
        throw new RuntimeException('Staff department or no-image guard differs from source');
    }
}
$hardware->execute([(string)$sourceStaff['uuid']]);
if ((int)$hardware->fetchColumn() !== 0) throw new RuntimeException('selected staff image state changed');
$staffAfter = (int)$db->query('SELECT COUNT(*) FROM ydy_staff WHERE is_show=1')->fetchColumn();
if ($staffAfter !== $visibleCount) throw new RuntimeException('visible staff count changed');
$typeMap = static function (array $row): array {
    $map = [];
    foreach ($row as $field => $value) $map[$field] = gettype($value);
    ksort($map);
    return $map;
};
$listTypes = $typeMap($listData[0]);
$detailTypes = $typeMap($detail);
echo json_encode(['lane' => $lane, 'http_business_ok' => 3,
    'source_visible_staff' => $visibleCount,
    'safe_page_index' => $candidate['page'],
    'list_wrapper_data_equal' => true,
    'source_department_verified' => true,
    'list_item_type_sha256' => hash('sha256', json_encode($listTypes)),
    'detail_type_sha256' => hash('sha256', json_encode($detailTypes)),
    'business_dml' => 0, 'external_image_reads' => 0], JSON_UNESCAPED_SLASHES), PHP_EOL;
