<?php

declare(strict_types=1);

set_exception_handler(static function (Throwable $error): void {
    fwrite(STDERR, 'N3_C_CLEANUP_READ_FAILED ' . get_class($error) . PHP_EOL);
    exit(2);
});

$marker = (string)($argv[1] ?? '');
if (!preg_match('/^CDXPARNUN3[A-F0-9]{8}$/D', $marker)) {
    throw new RuntimeException('Invalid exact synthetic marker');
}
$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_BASE_URL'] ?? '') !== 'http://127.0.0.1:18102'
    || ($env['POC_DIALECT'] ?? '') !== 'dm'
    || ($env['POC_AI_HOST'] ?? '') !== '127.0.0.1'
    || ($env['POC_AI_PORT'] ?? '') !== '5238'
    || ($env['POC_AI_SCHEMA'] ?? '') !== 'AIZHCT_APP'
    || ($env['POC_AI_USER'] ?? '') !== 'AIZHCT_APP') {
    throw new RuntimeException('Unapproved C AI boundary');
}
$db = new PDO('dm:host=127.0.0.1;port=5238;schema=AIZHCT_APP',
    $env['POC_AI_USER'], $env['POC_AI_PASSWORD'],
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_CASE => PDO::CASE_LOWER]);
if ((string)$db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")
    ->fetchColumn() !== 'AIZHCT_APP') {
    throw new RuntimeException('C actual schema mismatch');
}
$counts = [];
foreach ([
    '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'],
    'dishes_marker' => ['YOSHOP_DISHES', 'NAME'],
] as $key => [$table, $field]) {
    $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table . ' WHERE ' . $field . '=?');
    $stmt->execute([$marker]);
    $counts[$key] = (int)$stmt->fetchColumn();
}
$stmt = $db->prepare('SELECT * FROM YOSHOP_DISHES WHERE ID=? AND STORE_ID=10001');
$stmt->execute([1]);
$dish = $stmt->fetch(PDO::FETCH_ASSOC) ?: null;
$dishHash = '';
if (is_array($dish)) {
    ksort($dish);
    $encoded = json_encode($dish, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    $dishHash = is_string($encoded) ? hash('sha256', $encoded) : '';
}
$expected = 'e21ffcea1d1ec9eda32b7733dee42440bf2a0543f32a73cd063c9fc2bccb8a01';
$pass = array_sum($counts) === 0 && hash_equals($expected, $dishHash);
echo json_encode(['marker' => $marker, 'table_marker_counts' => $counts,
    'readonly_dish_id' => 1, 'readonly_dish_hash_unchanged' => $dishHash === $expected,
    'pass' => $pass], JSON_UNESCAPED_SLASHES) . PHP_EOL;
exit($pass ? 0 : 1);
