<?php

declare(strict_types=1);

$lane = $argv[1] ?? '';
if (!in_array($lane, ['B', 'C'], true)) exit(2);
$root = '/tmp/cdx-train-alias-20261012-' . $lane;
$pid = (int)file_get_contents($root . '/private-http.pid');
$cmdline = (string)file_get_contents('/proc/' . $pid . '/cmdline');
if (strpos($cmdline, $root . '/public') === false) throw new RuntimeException('Wrong private HTTP owner');
foreach (explode("\0", (string)file_get_contents('/proc/' . $pid . '/environ')) as $pair) {
    $parts = explode('=', $pair, 2);
    if (count($parts) === 2 && strpos($parts[0], 'POC_') === 0) putenv($pair);
}
$dialect = $lane === 'B' ? 'mysql' : 'dm';
$config = require $root . '/application/database.php';
$dsn = static function (array $c) use ($dialect): string {
    return $dialect === 'dm'
        ? 'dm:host=' . $c['hostname'] . ';port=' . $c['hostport'] . ';schema=' . $c['database']
        : 'mysql:host=' . $c['hostname'] . ';port=' . ($c['hostport'] ?? 3306)
            . ';dbname=' . $c['database'] . ';charset=utf8mb4';
};
$connect = static function (array $c) use ($dsn): PDO {
    return new PDO($dsn($c), $c['username'], $c['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
};
$store = $connect($config);
$ai = $connect($config['ai_zhct']);
$table = static function (string $name, bool $isAi = false) use ($dialect): string {
    $prefix = $isAi ? 'yoshop_' : 'ydy_';
    return $dialect === 'dm' ? strtoupper($prefix . $name) : $prefix . $name;
};
$one = static function (PDO $db, string $sql, array $params = []): array {
    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    return array_change_key_case($stmt->fetch(PDO::FETCH_ASSOC) ?: [], CASE_LOWER);
};
$actorId = $lane === 'B' ? 97260 : 2791;
$actor = $one($store, 'SELECT ID,UUID,ACCOUNT,NAME,TYPE,STAFF_UUID FROM '
    . $table('user') . ' WHERE ID=?', [$actorId]);
if (!$actor || strpos((string)$actor['account'], 'CDX') !== 0
    || (int)$actor['type'] !== 0 || (string)$actor['uuid'] === '') {
    throw new RuntimeException('Existing synthetic superadmin actor unavailable: '
        . json_encode(['found' => (bool)$actor,
            'uuid_marker' => strpos((string)($actor['uuid'] ?? ''), 'CDX') === 0,
            'account_marker' => strpos((string)($actor['account'] ?? ''), 'CDX') === 0,
            'type_zero' => (int)($actor['type'] ?? -1) === 0]));
}
require_once $root . '/application/base/Security.php';
$token = \app\base\Security::encrypt(implode("\t", [
    (string)$actor['id'], (string)$actor['uuid'], (string)$actor['name'],
    '0', '', (string)$actor['staff_uuid'], (string)$actor['name'],
]));
$base = 'http://127.0.0.1:' . ($lane === 'B' ? 19121 : 19122);
$boundary = json_decode((string)file_get_contents($base . '/__poc_boundary'), true);
if (empty($boundary['external_stubs']) || empty($boundary['redis_isolated'])
    || !empty($boundary['real_queue'])) throw new RuntimeException('Private boundary unavailable');
$post = static function (string $path, array $params = []) use ($base, $token): array {
    $context = stream_context_create(['http' => [
        'method' => 'POST', 'ignore_errors' => true, 'timeout' => 120,
        'header' => "Content-Type: application/x-www-form-urlencoded\r\n"
            . 'token: ' . $token . "\r\n",
        'content' => http_build_query($params, '', '&', PHP_QUERY_RFC3986),
    ]]);
    $body = file_get_contents($base . $path, false, $context);
    $status = 0;
    foreach (($http_response_header ?? []) as $header) {
        if (preg_match('/^HTTP\/\S+ (\d{3})/', $header, $match)) $status = (int)$match[1];
    }
    $json = is_string($body) ? json_decode($body, true) : null;
    $jsonError = json_last_error_msg();
    return ['status' => $status, 'json' => $json, 'bytes' => strlen((string)$body),
        'body_sha256' => hash('sha256', (string)$body),
        'leading_byte' => $body === false || $body === '' ? null : bin2hex($body[0]),
        'json_error' => $jsonError];
};
$results = [];
foreach (['add', 'update', 'status', 'delete'] as $action) {
    $response = $post('/p/trainunit/' . $action, [
        'uuid' => 'CDXTRAINROUTE20261012-' . $lane,
        'name' => 'CDXTRAINROUTE20261012-' . $lane,
        'status' => '1',
    ]);
    $results['trainunit_' . $action] = [
        'http' => $response['status'],
        'code' => $response['json']['code'] ?? null,
        'json' => is_array($response['json']),
        'bytes' => $response['bytes'],
        'body_sha256' => $response['body_sha256'],
    ];
}
$methods = $post('/p/payment/methods');
$methodRows = $methods['json']['data'] ?? null;
$results['payment_methods'] = ['http' => $methods['status'],
    'code' => $methods['json']['code'] ?? null,
    'bytes' => $methods['bytes'], 'leading_byte' => $methods['leading_byte'],
    'json_error' => $methods['json_error'],
    'count' => is_array($methodRows) ? count($methodRows) : null,
    'row_fields' => is_array($methodRows) && isset($methodRows[0])
        ? array_map('gettype', $methodRows[0]) : [],
];
$departments = $post('/p/walletFlow/departments');
$departmentRows = $departments['json']['data'] ?? null;
$stmt = $store->query('SELECT UUID,NAME FROM ' . $table('department'));
$dbDepartments = [];
foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $row) {
    $row = array_change_key_case($row, CASE_LOWER);
    $dbDepartments[(string)$row['uuid']] = (string)$row['name'];
}
$httpDepartments = [];
foreach ((array)$departmentRows as $row) {
    if (is_array($row) && isset($row['uuid'], $row['name'])) {
        $httpDepartments[(string)$row['uuid']] = (string)$row['name'];
    }
}
ksort($dbDepartments);
ksort($httpDepartments);
$results['wallet_departments'] = [
    'http' => $departments['status'], 'code' => $departments['json']['code'] ?? null,
    'bytes' => $departments['bytes'], 'leading_byte' => $departments['leading_byte'],
    'json_error' => $departments['json_error'],
    'count' => is_array($departmentRows) ? count($departmentRows) : null,
    'db_count' => count($dbDepartments), 'exact_source_match' => $dbDepartments === $httpDepartments,
    'row_fields' => is_array($departmentRows) && isset($departmentRows[0])
        ? array_map('gettype', $departmentRows[0]) : [],
];
if (getenv('POC_SKIP_ROLE') !== '1') {
    $role = $post('/p/role/departmentStaffs');
    $roleData = $role['json']['data'] ?? null;
    $results['role_department_staffs'] = [
        'http' => $role['status'], 'code' => $role['json']['code'] ?? null,
        'bytes' => $role['bytes'], 'leading_byte' => $role['leading_byte'],
        'json_error' => $role['json_error'],
        'keys' => is_array($roleData) ? array_keys($roleData) : [],
        'counts' => is_array($roleData) ? array_map(static function ($v) {
            return is_array($v) ? count($v) : null;
        }, $roleData) : [],
        'body_sha256' => $role['body_sha256'],
    ];
}
$marker = $lane === 'B' ? 'CDXPAYD914599B' : 'CDXPAY03721E84';
$staff = $one($store, 'SELECT AI_USER_ID FROM ' . $table('staff')
    . ' WHERE NAME=? AND IS_SHOW=1', [$marker]);
if (!$staff || (int)$staff['ai_user_id'] <= 0) throw new RuntimeException('Synthetic subsidy staff unavailable');
$subsidy = $post('/p/subsidy/list', ['nickname' => $marker,
    'start_date' => '2026-09-30', 'end_date' => '2026-09-30', 'page' => '1']);
$subsidyRows = $subsidy['json']['data']['data'] ?? null;
$sum = $one($ai, 'SELECT COALESCE(SUM(MONEY),0) AS SUM_MONEY,'
    . ' COALESCE(SUM(USED_MONEY),0) AS SUM_USED_MONEY,COUNT(*) AS N FROM '
    . $table('user_subsidy', true) . ' WHERE USER_ID=? AND IS_DELETE=0 AND PUSH_DATE BETWEEN ? AND ?',
    [(int)$staff['ai_user_id'], '2026-09-30', '2026-09-30']);
$matched = [];
foreach ((array)$subsidyRows as $row) {
    if (is_array($row) && (int)($row['user_id'] ?? 0) === (int)$staff['ai_user_id']) {
        $matched = $row;
        break;
    }
}
$moneyMatch = $matched
    && bccomp((string)$matched['sum_money'], (string)$sum['sum_money'], 2) === 0
    && bccomp((string)$matched['sum_used_money'], (string)$sum['sum_used_money'], 2) === 0;
$results['subsidy_list'] = [
    'http' => $subsidy['status'], 'code' => $subsidy['json']['code'] ?? null,
    'bytes' => $subsidy['bytes'], 'leading_byte' => $subsidy['leading_byte'],
    'json_error' => $subsidy['json_error'],
    'rows' => is_array($subsidyRows) ? count($subsidyRows) : null,
    'source_rows' => (int)$sum['n'], 'synthetic_row' => (bool)$matched,
    'money_readback' => (bool)$moneyMatch,
    'row_fields' => $matched ? array_map('gettype', $matched) : [],
    'amounts' => $matched ? [
        'sum_money' => (string)$matched['sum_money'],
        'sum_used_money' => (string)$matched['sum_used_money'],
        'subsidy_amount' => (string)$matched['subsidy_amount'],
    ] : [],
];
echo json_encode(['lane' => $lane, 'source' => 'fresh private runtime',
    'real_auth' => true, 'results' => $results],
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
