<?php

declare(strict_types=1);

$marker = (string)getenv('POC_MARKER');
if (!preg_match('/^CDXPARNUN3[A-F0-9]{8}$/', $marker)) {
    throw new RuntimeException('Synthetic marker invalid');
}
$env = [];
foreach (explode("\0", (string)@file_get_contents('/proc/53772/environ')) as $item) {
    $parts = explode('=', $item, 2);
    if (count($parts) === 2) $env[$parts[0]] = $parts[1];
}
if (($env['POC_TARGET_ROOT'] ?? '') !== '/tmp/zhct-ai-http-20260929.3XDj3w'
    || ($env['POC_DIALECT'] ?? '') !== 'dm'
    || ($env['POC_AI_PORT'] ?? '') !== '5238'
    || ($env['POC_AI_SCHEMA'] ?? '') !== 'AIZHCT_APP') {
    throw new RuntimeException('C AI boundary mismatch');
}
$db = new PDO('dm:host=' . $env['POC_AI_HOST'] . ';port=' . $env['POC_AI_PORT']
    . ';schema=' . $env['POC_AI_SCHEMA'], $env['POC_AI_USER'],
    $env['POC_AI_PASSWORD'], [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_CASE => PDO::CASE_LOWER]);
$predicates = [
    'operator' => ['YOSHOP_STORE_USER', 'USER_NAME'],
    'staff' => ['YOSHOP_STAFF', 'NAME'],
    'weight' => ['YOSHOP_STAFF_WEIGHT', 'CREATE_BY'],
    'meal' => ['YOSHOP_MEAL', 'CREATE_BY'],
    'meal_infos' => ['YOSHOP_MEAL_INFOS', 'CREATE_BY'],
];
$counts = [];
foreach ($predicates as $name => [$table, $field]) {
    $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table . ' WHERE ' . $field . '=?');
    $stmt->execute([$marker]);
    $counts[$name] = (int)$stmt->fetchColumn();
}
$stmt = $db->prepare('SELECT * FROM YOSHOP_DISHES WHERE ID=?');
$stmt->execute([1]);
$dish = $stmt->fetch(PDO::FETCH_ASSOC);
$dishHashMatch = false;
if (is_array($dish)) {
    ksort($dish);
    $encoded = json_encode($dish, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $dishHashMatch = is_string($encoded)
        && hash('sha256', $encoded)
            === 'e21ffcea1d1ec9eda32b7733dee42440bf2a0543f32a73cd063c9fc2bccb8a01';
}
echo json_encode(['mode' => 'independent-C-N3-marker-zero',
    'marker' => $marker, 'counts' => $counts,
    'readonly_dish_id' => 1, 'readonly_dish_hash_unchanged' => $dishHashMatch],
    JSON_UNESCAPED_SLASHES) . PHP_EOL;
exit(array_sum($counts) === 0 && $dishHashMatch ? 0 : 1);
