<?php

declare(strict_types=1);

$marker = (string)getenv('POC_MARKER');
if (!preg_match('/^CDXPARDSH[A-F0-9]{8}$/', $marker)) {
    throw new RuntimeException('Synthetic marker invalid');
}
$pid = (string)getenv('POC_RUNTIME_PID');
if (!ctype_digit($pid) || (int)$pid <= 1) throw new RuntimeException('AI PID missing');
$env = [];
foreach (explode("\0", (string)@file_get_contents('/proc/' . $pid . '/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_SCHEMA'] ?? '') !== 'AIZHCT_APP'
    || ($env['POC_AI_PORT'] ?? '') !== '5238') {
    throw new RuntimeException('C AI boundary failed');
}
$dsn = 'dm:host=' . $env['POC_AI_HOST'] . ';port=' . $env['POC_AI_PORT']
    . ';schema=' . $env['POC_AI_SCHEMA'];
$db = new PDO($dsn, $env['POC_AI_USER'], $env['POC_AI_PASSWORD'],
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$predicates = [
    'user' => ['YOSHOP_USER', 'NICK_NAME'],
    'dishes' => ['YOSHOP_DISHES', 'NAME'],
    'foods' => ['YOSHOP_FOODS', 'NAME'],
    'relation' => ['YOSHOP_DISHES_FOODS', 'CREATE_BY'],
    'tag' => ['YOSHOP_DISHES_TAG', 'CREATE_BY'],
];
$counts = [];
foreach ($predicates as $name => [$table, $column]) {
    $stmt = $db->prepare('SELECT COUNT(*) FROM ' . $table . ' WHERE ' . $column . '=?');
    $stmt->execute([$marker]);
    $counts[$name] = (int)$stmt->fetchColumn();
}
echo json_encode(['mode' => 'independent-C-read-only-marker-zero',
    'marker' => $marker, 'counts' => $counts], JSON_UNESCAPED_SLASHES) . PHP_EOL;
exit(array_sum($counts) === 0 ? 0 : 1);
