<?php

declare(strict_types=1);

// N3 only: C non-production metadata/COUNT preflight, no business HTTP or DML.
set_exception_handler(static function (Throwable $error): void {
    fwrite(STDERR, 'AI_N3_PREFLIGHT_FAILED ' . get_class($error) . PHP_EOL);
    exit(2);
});
$root = '/tmp/zhct-ai-http-20260929.3XDj3w';
$base = 'http://127.0.0.1:18102';
$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'] ?? '') !== $root
    || ($env['POC_BASE_URL'] ?? '') !== $base
    || ($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');
}
$boundaryRaw = @file_get_contents($base . '/__poc_boundary', false,
    stream_context_create(['http' => ['timeout' => 5]]));
$boundary = is_string($boundaryRaw) ? json_decode($boundaryRaw, true) : null;
unset($boundaryRaw);
if (!is_array($boundary) || empty($boundary['external_stubs'])) {
    throw new RuntimeException('C external isolation absent');
}
$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]);
if ((string)$db->query("SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")
    ->fetchColumn() !== 'AIZHCT_APP') {
    throw new RuntimeException('C actual schema mismatch');
}
$count = static function (string $sql, array $args = []) use ($db): int {
    $stmt = $db->prepare($sql);
    $stmt->execute($args);
    return (int)$stmt->fetchColumn();
};
$needed = [
    'store' => ['STORE_ID'],
    'store_user' => ['STORE_USER_ID', 'USER_NAME', 'PASSWORD', 'IS_SUPER',
        'STORE_ID', 'IS_DELETE'],
    'store_api' => ['API_ID', 'URL'],
    'staff' => ['ID', 'NAME', 'STORE_ID', 'IS_DELETE'],
    'staff_weight' => ['ID', 'STAFF_ID', 'SET_DATE', 'HEIGHT', 'WEIGHT',
        'STORE_ID', 'IS_DELETE', 'CREATE_BY'],
    'meal' => ['ID', 'STAFF_ID', 'MEAL_DATE', 'MEAL_TIMES', 'STORE_ID',
        'IS_DELETE', 'CREATE_BY'],
    'meal_infos' => ['ID', 'MEAL_ID', 'STAFF_ID', 'MEAL_DATE', 'MEAL_TIMES',
        'DISHES_ID', 'DISHES_WEIGHT', 'CATEGORY', 'STORE_ID', 'IS_DELETE'],
    'dishes' => ['ID', 'NAME', 'CATEGORY', 'WEIGHT', 'STORE_ID', 'IS_DELETE'],
    'dishes_cate' => ['ID', 'PID'],
];
$tableOk = [];
$triggerCounts = [];
foreach ($needed as $short => $columns) {
    $table = 'YOSHOP_' . strtoupper($short);
    $exists = $count('SELECT COUNT(*) FROM USER_TABLES WHERE TABLE_NAME=?', [$table]) === 1;
    $columnOk = false;
    $triggerCounts[$short] = null;
    if ($exists) {
        $stmt = $db->prepare('SELECT COLUMN_NAME FROM USER_TAB_COLUMNS WHERE TABLE_NAME=?');
        $stmt->execute([$table]);
        $actual = array_map('strtoupper', $stmt->fetchAll(PDO::FETCH_COLUMN));
        $columnOk = count(array_diff($columns, $actual)) === 0;
        $triggerCounts[$short] = $count('SELECT COUNT(*) FROM USER_TRIGGERS'
            . " WHERE TABLE_NAME=? AND STATUS='ENABLED'", [$table]);
    }
    $tableOk[$short] = $exists && $columnOk;
}
$routes = ['weight.staff_weight/list', 'weight.staff_weight/echartsList',
    'meal.meals/mealsInfo'];
$acl = [];
if ($tableOk['store_api']) {
    foreach ($routes as $route) {
        $acl[$route] = $count('SELECT COUNT(*) FROM YOSHOP_STORE_API WHERE URL=?',
            ['/' . $route]);
    }
}
$marker = 'CDXPARNUN3' . strtoupper(bin2hex(random_bytes(4)));
$markerZero = [];
foreach (['store_user' => 'USER_NAME', 'staff' => 'NAME',
    'dishes' => 'NAME'] as $short => $field) {
    $markerZero[$short] = $tableOk[$short]
        ? $count('SELECT COUNT(*) FROM YOSHOP_' . strtoupper($short)
            . ' WHERE ' . $field . '=?', [$marker]) === 0 : null;
}
$catalog = [
    'store_10001' => $tableOk['store']
        ? $count('SELECT COUNT(*) FROM YOSHOP_STORE WHERE STORE_ID=?', [10001]) : null,
    'dishes_top_category_count' => $tableOk['dishes_cate']
        ? $count('SELECT COUNT(*) FROM YOSHOP_DISHES_CATE WHERE PID=0') : null,
];
echo json_encode(['suite' => 'ai-store-n3-C', 'mode' => 'read-only-preflight',
    'tables_and_columns' => $tableOk, 'enabled_trigger_counts' => $triggerCounts,
    'acl_api_rows' => $acl, 'catalog_counts' => $catalog,
    'fresh_marker_zero' => $markerZero, 'external_stubs' => true],
    JSON_UNESCAPED_SLASHES) . PHP_EOL;
$pass = !in_array(false, $tableOk, true)
    && !in_array(false, $markerZero, true)
    && $catalog['store_10001'] === 1
    && (int)$catalog['dishes_top_category_count'] > 0
    && array_sum(array_map('intval', $triggerCounts)) === 0;
exit($pass ? 0 : 1);
