<?php
declare(strict_types=1);

// Read-only nonproduction C boundary/schema probe. No business HTTP or DML.
$stage = 'bootstrap';
set_exception_handler(static function (Throwable $error) use (&$stage): void {
    echo json_encode(['status' => 'redacted-error', 'stage' => $stage,
        'class' => get_class($error), 'code' => (string)$error->getCode()]), PHP_EOL;
    exit(2);
});
set_error_handler(static function (int $severity): bool {
    if (!(error_reporting() & $severity)) return false;
    throw new ErrorException('redacted warning', 0, $severity);
});
$root = '/tmp/zhct-ai-http-20260929.3XDj3w';
$pid = 53772;
$stage = 'nonproduction_process';
$cmdline = file_get_contents('/proc/' . $pid . '/cmdline');
if (!is_string($cmdline)
    || strpos($cmdline, $root . '/public') === false
    || strpos($cmdline, '127.0.0.1:18102') === false) {
    throw new RuntimeException('Isolated C process identity mismatch');
}
$raw = file_get_contents('/proc/' . $pid . '/environ');
if (!is_string($raw)) throw new RuntimeException('Isolated C environment unavailable');
$config = [];
foreach (explode("\0", $raw) as $entry) {
    if (strpos($entry, 'POC_') !== 0) continue;
    $equal = strpos($entry, '=');
    if ($equal !== false) $config[substr($entry, 0, $equal)] = substr($entry, $equal + 1);
}
$required = [
    'POC_DIALECT' => 'dm', 'POC_EXTERNAL_STUBS' => '1',
    'POC_AI_HOST' => '127.0.0.1', 'POC_AI_PORT' => '5238',
    'POC_AI_SCHEMA' => 'AIZHCT_APP',
    'POC_HOST' => '127.0.0.1', 'POC_PORT' => '5237',
    'POC_SCHEMA' => 'ZHCT_APP',
];
foreach ($required as $key => $expected) {
    if (($config[$key] ?? null) !== $expected) {
        throw new RuntimeException('Nonproduction C database boundary mismatch');
    }
}
foreach (['POC_AI_USER', 'POC_AI_PASSWORD', 'POC_USER', 'POC_PASSWORD'] as $key) {
    if (empty($config[$key])) throw new RuntimeException('C credential unavailable');
}
$stage = 'external_stub_boundary';
$boundary = json_decode((string)file_get_contents(
    'http://127.0.0.1:18102/__poc_boundary'), true);
if (!is_array($boundary) || empty($boundary['external_stubs'])) {
    throw new RuntimeException('External stub unavailable');
}
$connect = static function (string $host, string $port, string $schema,
    string $user, string $password): PDO {
    return new PDO('dm:host=' . $host . ';port=' . $port . ';schema=' . $schema,
        $user, $password, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
};
$identity = static function (PDO $pdo, string $expected): void {
    $user = strtoupper((string)$pdo->query('SELECT USER FROM DUAL')->fetchColumn());
    $schema = strtoupper((string)$pdo->query(
        "SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")->fetchColumn());
    if ($user !== $expected || $schema !== $expected) {
        throw new RuntimeException('Connected user/schema mismatch');
    }
};
$stage = 'ai_database_identity';
$ai = $connect($config['POC_AI_HOST'], $config['POC_AI_PORT'],
    $config['POC_AI_SCHEMA'], $config['POC_AI_USER'], $config['POC_AI_PASSWORD']);
$identity($ai, 'AIZHCT_APP');
$stage = 'store_database_identity';
$store = $connect($config['POC_HOST'], $config['POC_PORT'],
    $config['POC_SCHEMA'], $config['POC_USER'], $config['POC_PASSWORD']);
$identity($store, 'ZHCT_APP');
$aiColumns = [
    'YOSHOP_USER' => 'USER_ID,STORE_ID,NICK_NAME,IS_DELETE',
    'YOSHOP_STAFF' => 'ID,USER_ID,STORE_ID,IS_DELETE,CREATE_TIME',
    'YOSHOP_MEAL' => 'ID,STAFF_ID,MEAL_DATE,MEAL_TIMES,IS_DELETE',
    'YOSHOP_MEAL_INFOS' => 'ID,MEAL_ID,STAFF_ID,MEAL_DATE,MEAL_TIMES,DISHES_ID,DISHES_WEIGHT,IS_DELETE',
    'YOSHOP_DISHES' => 'ID,NAME,WEIGHT,IS_DELETE',
];
$storeColumns = [
    'YDY_MEASUREMENT_SESSION' => 'SESSION_ID,AI_USER_ID,IS_VALID,DEVICE_TYPE,START_TIME',
    'YDY_MEASUREMENT_SESSION_RAW' => 'ID,SESSION_ID',
    'YDY_HEALTH_RECORD' => 'RECORD_ID,SESSION_ID',
];
$aiTransitiveTables = [
    'YOSHOP_MEAL_RECOMMEND', 'YOSHOP_MEAL_SCORE_SUBTABLE',
    'YOSHOP_DIETARY_RECOMMEND', 'YOSHOP_DISHES_CATE',
    'YOSHOP_DISHES_FOODS', 'YOSHOP_FOODS',
    'YOSHOP_CONFIG_ENUM', 'YOSHOP_UPLOAD_FILE',
];
foreach ($aiColumns as $table => $columns) {
    $stage = 'ai_columns_' . strtolower($table);
    $ai->query('SELECT ' . $columns . ' FROM ' . $table . ' WHERE 1=0');
}
foreach ($aiTransitiveTables as $table) {
    $stage = 'ai_transitive_table_' . strtolower($table);
    $ai->query('SELECT 1 FROM ' . $table . ' WHERE 1=0');
}
foreach ($storeColumns as $table => $columns) {
    $stage = 'store_columns_' . strtolower($table);
    $store->query('SELECT ' . $columns . ' FROM ' . $table . ' WHERE 1=0');
}
echo json_encode(['status' => 'health-read-c-readonly-preflight-pass',
    'isolated_runtime' => true, 'external_stubs' => true,
    'ai_schema_identity' => true, 'store_schema_identity' => true,
    'ai_table_column_groups' => count($aiColumns),
    'ai_transitive_tables' => count($aiTransitiveTables),
    'store_table_column_groups' => count($storeColumns),
    'business_http_count' => 0, 'business_row_reads' => 0,
    'writes' => 0], JSON_UNESCAPED_SLASHES), PHP_EOL;
