<?php

declare(strict_types=1);

// Read-only A/B/C natural-source and exact read-menu inventory.
$lane = (string)getenv('CDX_READ4_LANE');
$mode = (string)($argv[1] ?? '');
$targets = [
    'A' => ['/tmp/zhct-http-store-a.l5omH8', 'http://127.0.0.1:18097', 21023,
        'mysql', '1c6d67b5fd01b261304b47623ff0e9e2ce6e1269d53d3b0937bfdf191fdea38b'],
    'B' => ['/tmp/zhct-http-store-mysql.dQTTBP', 'http://127.0.0.1:18081', 10001,
        'mysql', 'a67e1dacaaf1c688bfdc8bdadbc9d05b8aea7c41e6f4aa44cb5586c9c06f075a'],
    'C' => ['/tmp/zhct-dm-poc-20260928.fcpiiN/store', 'http://127.0.0.1:18080', 112175,
        'dm', 'a67e1dacaaf1c688bfdc8bdadbc9d05b8aea7c41e6f4aa44cb5586c9c06f075a'],
];
if (!in_array($mode, ['--preflight', '--embedded-preflight'], true)
    || ($mode === '--embedded-preflight'
        && (string)getenv('CDX_READ4_EMBEDDED') !== 'ONLY_FROM_REVIEWED_HARNESS')
    || !isset($targets[$lane])) {
    fwrite(STDERR, "Birthday/questionnaire business HTTP and DML disabled\n");
    exit(78);
}
[$root, $base, $pid, $dialect, $questionLogicSha] = $targets[$lane];
if ((string)getenv('POC_APP_ROOT') !== $root
    || (string)getenv('POC_BASE_URL') !== $base
    || (string)getenv('POC_DIALECT') !== $dialect
    || is_link($root)
    || hash_file('sha256', $root . '/application/p/controller/BirthdayDish.php')
        !== '69d93343e2dd377cff7645cde5a232f7a02e9bf17b808a73c94999b001f6e468'
    || hash_file('sha256', $root . '/application/p/logic/BirthdayDish.php')
        !== '678e45a8743741633597bbd76d8242d1d67060517ba2f15996136efc467e2d04'
    || hash_file('sha256', $root . '/application/p/controller/DishQuestionnaire.php')
        !== '1f2c402c7ab410bd99fbb7a60f16efc5d1b3117f277063456f3994118b47dde5'
    || hash_file('sha256', $root . '/application/p/logic/DishQuestionnaire.php')
        !== $questionLogicSha
    || hash_file('sha256', $root . '/application/common/service/DishQuestionnairePolicy.php')
        !== 'f9ad254a3b4ce3021e57e15f1f7e8a94f56807b763f024aaf7b689a929aed40c'
    || hash_file('sha256', $root . '/application/base/AdminController.php')
        !== '7565b36fa4dda2c21cc4fa3b37753dbffb7c3a464bb8c11ea0f17ca00bececa5') {
    throw new RuntimeException('Approved read4 source/runtime drift');
}
$cmdline = (string)@file_get_contents('/proc/' . $pid . '/cmdline');
$environment = (string)@file_get_contents('/proc/' . $pid . '/environ');
$children = (string)@file_get_contents('/proc/' . $pid . '/task/' . $pid . '/children');
$boundary = json_decode((string)@file_get_contents($base . '/__poc_boundary'), true);
$port = (int)parse_url($base, PHP_URL_PORT);
$hex = strtoupper(str_pad(dechex($port), 4, '0', STR_PAD_LEFT));
$inode = '';
foreach (@file('/proc/net/tcp', FILE_IGNORE_NEW_LINES) ?: [] as $line) {
    $parts = preg_split('/\s+/', trim($line));
    if (($parts[1] ?? '') === '0100007F:' . $hex && ($parts[3] ?? '') === '0A') {
        $inode = (string)($parts[9] ?? '');
        break;
    }
}
$ownsPort = false;
if ($inode !== '') foreach (@scandir('/proc/' . $pid . '/fd') ?: [] as $fd) {
    if ($fd !== '.' && $fd !== '..'
        && @readlink('/proc/' . $pid . '/fd/' . $fd) === 'socket:[' . $inode . ']') {
        $ownsPort = true;
        break;
    }
}
if (strpos($cmdline, '127.0.0.1:' . $port) === false
    || strpos($cmdline, $root . '/public') === false
    || $environment === '' || trim($children) !== ''
    || preg_match('/(?:^|\x00)PHP_CLI_SERVER_WORKERS=([2-9]|\d{2,})(?:\x00|$)/',
        $environment) || !$ownsPort || !is_array($boundary)
    || empty($boundary['external_stubs']) || empty($boundary['redis_isolated'])
    || !empty($boundary['real_queue'])) {
    throw new RuntimeException('Read4 isolated HTTP boundary absent');
}
$runtime = require $root . '/application/database.php';
if (!is_array($runtime) || (string)($runtime['prefix'] ?? '') !== 'ydy_') {
    throw new RuntimeException('Read4 runtime DB config invalid');
}
if ($dialect === 'mysql') {
    $local = require '/workspace/zhct/zhctproject/store/application/config/local/database.php';
    if (!is_array($local) || (string)($runtime['type'] ?? '') !== 'mysql') {
        throw new RuntimeException('Read4 code local MySQL required');
    }
    foreach (['hostname', 'database', 'username', 'password'] as $key) {
        if (($runtime[$key] ?? null) !== ($local[$key] ?? null)) {
            throw new RuntimeException('Read4 runtime differs from code local');
        }
    }
    if ((int)($runtime['hostport'] ?? 3306) !== (int)($local['hostport'] ?? 3306)) {
        throw new RuntimeException('Read4 MySQL port mismatch');
    }
    $dsn = 'mysql:host=' . $runtime['hostname'] . ';port='
        . (int)($runtime['hostport'] ?? 3306) . ';dbname=' . $runtime['database']
        . ';charset=' . (string)($runtime['charset'] ?? 'utf8');
    $approved = '003eb5aecf1cd4595b609c1f7f20b9ee325b578309fb9fe14fedaf77584fa401';
} else {
    if ((string)($runtime['type'] ?? '') !== 'app\\cores\\database\\Dm'
        || (string)getenv('POC_HOST') !== '127.0.0.1'
        || (string)getenv('POC_PORT') !== '5237'
        || strtoupper((string)getenv('POC_SCHEMA')) !== 'ZHCT_APP'
        || strtoupper((string)getenv('POC_USER')) !== 'ZHCT_APP') {
        throw new RuntimeException('Read4 DM target mismatch');
    }
    foreach (['hostname' => 'POC_HOST', 'hostport' => 'POC_PORT',
        'database' => 'POC_SCHEMA', 'username' => 'POC_USER',
        'password' => 'POC_PASSWORD'] as $key => $envKey) {
        if ((string)($runtime[$key] ?? '') !== (string)getenv($envKey)) {
            throw new RuntimeException('Read4 DM worker context mismatch');
        }
    }
    $machine = trim((string)@file_get_contents('/etc/machine-id'));
    if ($machine === '' || gethostname() === false
        || hash('sha256', gethostname() . '|' . $machine)
            !== 'd56d81988bb0f106946cce91c608fdd0ef1116e5150b23376ea87e086eace4b9') {
        throw new RuntimeException('Read4 DM host mismatch');
    }
    $listeners = [];
    $listenerExit = 0;
    @exec('/usr/sbin/ss -ltnp 2>/dev/null', $listeners, $listenerExit);
    $localDm = false;
    if ($listenerExit === 0) foreach ($listeners as $listener) {
        if (preg_match('/\*:5237\s+.*users:\(\("dmserver",pid=(\d+),/',
            $listener, $match)) {
            $exe = @readlink('/proc/' . $match[1] . '/exe');
            $localDm = is_string($exe) && basename($exe) === 'dmserver';
            break;
        }
    }
    if (!$localDm) throw new RuntimeException('Read4 DM listener not local');
    $dsn = 'dm:host=127.0.0.1;port=5237;schema=ZHCT_APP';
    $approved = 'bc98485aed26beab348770a82ae38dbf922b04ab88a210cd7282c4caf0156194';
}
$db = new PDO($dsn, (string)$runtime['username'],
    (string)$runtime['password'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_CASE => PDO::CASE_LOWER, PDO::ATTR_TIMEOUT => 5]);
$identity = $dialect === 'mysql'
    ? (string)$db->query(
        "SELECT CONCAT(@@server_uuid,'|',@@hostname,'|',@@port,'|',DATABASE())"
    )->fetchColumn()
    : 'ZHCT_APP|5237|' . (string)$db->query(
        "SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL"
    )->fetchColumn();
if (!hash_equals($approved, hash('sha256', $identity))) {
    throw new RuntimeException('Read4 DB identity outside approved target');
}
$p = $dialect === 'dm' ? 'YDY_' : 'ydy_';
$read = static function (string $sql, array $args = []) use ($db): array {
    $stmt = $db->prepare($sql);
    $stmt->execute($args);
    $rows = [];
    foreach ($stmt->fetchAll(PDO::FETCH_ASSOC) as $raw) {
        $row = [];
        foreach (array_change_key_case($raw, CASE_LOWER) as $key => $value) {
            $row[$key] = is_resource($value) ? stream_get_contents($value) : $value;
        }
        $rows[] = $row;
    }
    return $rows;
};
$count = static function (string $sql, array $args = []) use ($db): int {
    $stmt = $db->prepare($sql);
    $stmt->execute($args);
    return (int)$stmt->fetchColumn();
};
$birthdayMenuUuid = 'A1344000-0000-0000-0000-000000000001';
$birthdayMenus = $read('SELECT UUID,FILTER,LINK FROM ' . $p . 'menu WHERE UUID=?',
    [$birthdayMenuUuid]);
$reviewMenus = $read('SELECT UUID,FILTER,LINK FROM ' . $p . 'menu'
    . ' WHERE LOWER(LINK)=?', ['/restaurantmanagement/diningreview']);
$hasBirthdayMenu = count($birthdayMenus) === 1
    && in_array('p/birthdaydish/dishoptions', array_map('trim',
        explode('|', strtolower((string)$birthdayMenus[0]['filter']))), true);
$hasReviewMenu = count($reviewMenus) === 1;
$activeRestaurants = $read('SELECT ID,UUID FROM ' . $p . 'restaurants'
    . ' WHERE STATUS=1 AND IS_DELETE=2 ORDER BY ID'
    . ($dialect === 'dm' ? ' FETCH FIRST 21 ROWS ONLY' : ' LIMIT 21'));
$activeDepartments = $read('SELECT UUID FROM ' . $p . 'department'
    . ' WHERE STATUS=1 AND IS_SHOW=1 ORDER BY ID'
    . ($dialect === 'dm' ? ' FETCH FIRST 21 ROWS ONLY' : ' LIMIT 21'));
$activeDishes = $read('SELECT ID,UUID,NAME,CATEGORY,CATEGORY_ONE,CATEGORY_TWO,FILE_PATH'
    . ' FROM ' . $p . 'dishes WHERE STORE_ID=10001 AND STATUS=1'
    . ' AND IS_DEL=1 AND IS_DELETE=0 ORDER BY NAME,ID'
    . ($dialect === 'dm' ? ' FETCH FIRST 21 ROWS ONLY' : ' LIMIT 21'));
$candidateRows = $read('SELECT q.ID,q.DISHES_UUID,q.RESTAURANT_ID,q.MEAL_DATE,'
    . ' q.MEAL_TIMES,q.SCORE FROM ' . $p . 'dish_questionnaire q'
    . ' JOIN ' . $p . 'restaurants r ON r.ID=q.RESTAURANT_ID'
    . ' WHERE q.STORE_ID=10001 AND q.IS_DELETE=0'
    . ' AND r.STATUS=1 AND r.IS_DELETE=2'
    . ' ORDER BY q.ID DESC'
    . ($dialect === 'dm' ? ' FETCH FIRST 21 ROWS ONLY' : ' LIMIT 21'));
$candidate = $candidateRows[0] ?? null;
$candidateGroupRows = [];
$candidateTagRows = [];
if ($candidate !== null) {
    $candidateGroupRows = $read('SELECT ID,DISHES_UUID,RESTAURANT_ID,MEAL_DATE,'
        . ' MEAL_TIMES,SCORE,DISHES_NAME_SNAPSHOT,CREATE_TIME'
        . ' FROM ' . $p . 'dish_questionnaire WHERE STORE_ID=10001 AND IS_DELETE=0'
        . ' AND RESTAURANT_ID=? AND DISHES_UUID=? AND MEAL_DATE=? AND MEAL_TIMES=?'
        . ' ORDER BY ID DESC'
        . ($dialect === 'dm' ? ' FETCH FIRST 101 ROWS ONLY' : ' LIMIT 101'),
        [(int)$candidate['restaurant_id'], (string)$candidate['dishes_uuid'],
            (string)$candidate['meal_date'], (int)$candidate['meal_times']]);
    $ids = array_column($candidateGroupRows, 'id');
    if ($ids) {
        $candidateTagRows = $read('SELECT QUESTIONNAIRE_ID,TAG_CODE,TAG_NAME_SNAPSHOT'
            . ' FROM ' . $p . 'dish_questionnaire_tag WHERE QUESTIONNAIRE_ID IN ('
            . implode(',', array_fill(0, count($ids), '?')) . ') ORDER BY QUESTIONNAIRE_ID,TAG_CODE',
            array_map('intval', $ids));
    }
}
$markerRows = $count('SELECT COUNT(*) FROM ' . $p . 'user'
    . " WHERE ACCOUNT LIKE 'CDXBDQ4%'");
$result = ['lane' => $lane, 'dialect' => $dialect,
    'approved_store_identity' => true,
    'isolated_http_boundary' => true,
    'source_sha_gate' => true,
    'birthday_menu_exact' => $hasBirthdayMenu,
    'review_menu_exact' => $hasReviewMenu,
    'review_menu_uuid_sha12' => $hasReviewMenu
        ? substr(hash('sha256', (string)$reviewMenus[0]['uuid']), 0, 12) : null,
    'active_restaurants_sample' => count($activeRestaurants),
    'active_departments_sample' => count($activeDepartments),
    'active_dishes_sample' => count($activeDishes),
    'dish_sample_sha' => hash('sha256', serialize($activeDishes)),
    'questionnaire_candidate_count_bounded' => count($candidateRows),
    'questionnaire_group_rows_bounded' => count($candidateGroupRows),
    'questionnaire_candidate_restaurant_id' => $candidate === null
        ? null : (int)$candidate['restaurant_id'],
    'questionnaire_candidate_dish_uuid_sha12' => $candidate === null
        ? null : substr(hash('sha256', (string)$candidate['dishes_uuid']), 0, 12),
    'questionnaire_candidate_date' => $candidate['meal_date'] ?? null,
    'questionnaire_candidate_meal_times' => $candidate === null
        ? null : (int)$candidate['meal_times'],
    'questionnaire_group_sha' => hash('sha256', serialize($candidateGroupRows)),
    'questionnaire_tag_rows' => count($candidateTagRows),
    'stale_synthetic_users' => $markerRows,
    'business_http_executed' => false, 'dml_executed' => false];
if ($mode === '--embedded-preflight') {
    return ['result' => $result, 'db' => $db, 'prefix' => $p,
        'dialect' => $dialect, 'root' => $root, 'base' => $base, 'pid' => $pid,
        'runtime' => $runtime, 'read' => $read, 'count' => $count,
        'birthday_menu' => $birthdayMenus[0] ?? null,
        'review_menu' => $reviewMenus[0] ?? null,
        'active_restaurants' => $activeRestaurants,
        'active_departments' => $activeDepartments,
        'active_dishes' => $activeDishes,
        'questionnaire_candidate' => $candidate,
        'questionnaire_group_rows' => $candidateGroupRows,
        'questionnaire_tag_rows' => $candidateTagRows];
}
echo json_encode($result, JSON_UNESCAPED_SLASHES), PHP_EOL;
