<?php
declare(strict_types=1);

// Read-only actual mobile dish detail smoke, no fixture or DB DML.
$lane = (string)($argv[1] ?? '');
if (!in_array($lane, ['B', 'C'], true)) {
    echo "DENIED business_http=0 business_dml=0\n"; exit(78);
}
if ($lane === 'B') {
    $c = include '/tmp/zhct-http-store-mysql.dQTTBP/application/config/local/database.php';
    if (!is_array($c) || ($c['database'] ?? '') !== 'zhct')
        throw new RuntimeException('B code-local Store DB drift');
    $db = new PDO('mysql:host=' . $c['hostname'] . ';port=3306;dbname='
        . $c['database'] . ';charset=utf8', $c['username'], $c['password'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
    $port = 18081;
    $limit = ' LIMIT 1';
} else {
    if (getenv('POC_DIALECT') !== 'dm' || getenv('POC_HOST') !== '127.0.0.1'
        || getenv('POC_PORT') !== '5237' || getenv('POC_SCHEMA') !== 'ZHCT_APP')
        throw new RuntimeException('C isolated Store DM 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;
    $limit = ' FETCH FIRST 1 ROWS ONLY';
}
$sql = 'SELECT uuid,name,category,weight FROM ydy_dishes'
    . ' WHERE is_del=1 AND status=1 AND category=1 AND weight>0'
    . ' ORDER BY id ASC' . $limit;
$dish = $db->query($sql)->fetch(PDO::FETCH_ASSOC);
if (!is_array($dish)) throw new RuntimeException('No bounded source dish');
$dish = array_change_key_case($dish, CASE_LOWER);
$ctx = stream_context_create(['http' => ['method' => 'POST',
    'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
    'content' => http_build_query(['dishes_uuid' => $dish['uuid']]),
    'ignore_errors' => true, 'timeout' => 18, 'follow_location' => 0]]);
$h = @fopen('http://127.0.0.1:' . $port . '/m/Dishes/dishes_info',
    'rb', false, $ctx);
if (!is_resource($h)) throw new RuntimeException('Mobile dish HTTP unavailable');
$raw = stream_get_contents($h, 1048577); fclose($h);
if (!is_string($raw) || strlen($raw) > 1048576)
    throw new RuntimeException('Mobile dish response too large');
$body = json_decode($raw, true);
if (!is_array($body)) throw new RuntimeException('Mobile dish non-JSON');
$data = $body['data'] ?? null;
$sourceMatch = is_array($data)
    && (string)($data['uuid'] ?? '') === (string)$dish['uuid']
    && (string)($data['name'] ?? '') === (string)$dish['name'];
$additional = [];
foreach ([[1, 'iron'], [2, ''], [3, ''], [4, ''], [5, ''], [6, '']] as $case) {
    list($category, $nutrient) = $case;
    $caseDish = $db->query('SELECT uuid,name FROM ydy_dishes WHERE is_del=1'
        . ' AND status=1 AND weight>0 AND category=' . $category
        . ' ORDER BY id ASC' . $limit)->fetch(PDO::FETCH_ASSOC);
    if (!is_array($caseDish)) throw new RuntimeException('Additional source category absent');
    $caseDish = array_change_key_case($caseDish, CASE_LOWER);
    $params = ['dishes_uuid' => $caseDish['uuid']];
    if ($nutrient !== '') $params['nutrient'] = $nutrient;
    $caseCtx = stream_context_create(['http' => ['method' => 'POST',
        'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
        'content' => http_build_query($params), 'ignore_errors' => true,
        'timeout' => 18, 'follow_location' => 0]]);
    $caseHandle = @fopen('http://127.0.0.1:' . $port . '/m/Dishes/dishes_info',
        'rb', false, $caseCtx);
    if (!is_resource($caseHandle)) throw new RuntimeException('Additional dish HTTP unavailable');
    $caseRaw = stream_get_contents($caseHandle, 1048577); fclose($caseHandle);
    $caseBody = is_string($caseRaw) && strlen($caseRaw) <= 1048576
        ? json_decode($caseRaw, true) : null;
    $caseData = $caseBody['data'] ?? null;
    if (!is_array($caseBody) || (int)($caseBody['code'] ?? -1) !== 0
        || !is_array($caseData)
        || (string)($caseData['uuid'] ?? '') !== (string)$caseDish['uuid']
        || (string)($caseData['name'] ?? '') !== (string)$caseDish['name']) {
        throw new RuntimeException('Additional dish detail differs from original source');
    }
    $additional[] = ['category' => $category, 'nutrient' => $nutrient,
        'keys' => array_keys($caseData), 'types' => array_map('gettype', $caseData),
        'source_uuid_name_equal' => true];
}
$topCtx = stream_context_create(['http' => ['method' => 'POST',
    'header' => "Content-Type: application/x-www-form-urlencoded\r\n",
    'content' => 'nutrient=protein', 'ignore_errors' => true,
    'timeout' => 18, 'follow_location' => 0]]);
$topHandle = @fopen('http://127.0.0.1:' . $port . '/m/Dishes/top5',
    'rb', false, $topCtx);
if (!is_resource($topHandle)) throw new RuntimeException('Top5 HTTP unavailable');
$topRaw = stream_get_contents($topHandle, 1048577); fclose($topHandle);
$topBody = is_string($topRaw) && strlen($topRaw) <= 1048576
    ? json_decode($topRaw, true) : null;
$topRows = $topBody['data'] ?? null;
if (!is_array($topBody) || (int)($topBody['code'] ?? -1) !== 0
    || !is_array($topRows) || !$topRows || count($topRows) > 5) {
    throw new RuntimeException('Top5 positive HTTP failed');
}
$topSource = $db->prepare('SELECT name FROM ydy_dishes WHERE uuid=?');
$topTypes = [];
foreach ($topRows as $item) {
    $topSource->execute([(string)($item['uuid'] ?? '')]);
    $sourceName = $topSource->fetchColumn();
    if ($sourceName === false || (string)$sourceName !== (string)($item['name'] ?? '')) {
        throw new RuntimeException('Top5 dish differs from original source');
    }
    $topTypes[json_encode(array_map('gettype', $item))] = true;
}
echo json_encode(['lane' => $lane, 'business_code' => $body['code'] ?? null,
    'message' => $body['message'] ?? null,
    'source_dish_uuid_sha' => hash('sha256', (string)$dish['uuid']),
    'data_keys' => is_array($data) ? array_keys($data) : [],
    'data_types' => is_array($data) ? array_map('gettype', $data) : [],
    'numeric_text_samples' => is_array($data) ? array_intersect_key($data,
        array_fill_keys(['energy', 'carbohydrate', 'protein', 'va', 'cholesterol'], true)) : [],
    'additional_cases' => $additional,
    'top5_count' => count($topRows),
    'top5_types' => array_keys($topTypes),
    'top5_all_source_uuid_name_equal' => true,
    'source_uuid_name_equal' => $sourceMatch,
    'business_http' => 8, 'business_dml' => 0], JSON_UNESCAPED_SLASHES), PHP_EOL;
