<?php

declare(strict_types=1);

// Read-only: one existing ID only, never print the ID, row, SQL, bind or message.
$root = '/tmp/zhct-ai-http-20260929.3XDj3w';
$pid = 53772;
$processEnv = [];
foreach (explode("\0", (string)@file_get_contents('/proc/' . $pid . '/environ')) as $item) {
    $parts = explode('=', $item, 2);
    if (count($parts) === 2) $processEnv[$parts[0]] = $parts[1];
}
if (($processEnv['POC_TARGET_ROOT'] ?? '') !== $root
    || ($processEnv['POC_DIALECT'] ?? '') !== 'dm'
    || ($processEnv['POC_AI_SCHEMA'] ?? '') !== 'AIZHCT_APP'
    || ($processEnv['POC_AI_PORT'] ?? '') !== '5238') {
    throw new RuntimeException('Unapproved isolated AI runtime');
}
foreach (['POC_TARGET_ROOT', 'POC_BASE_URL', 'POC_DIALECT',
    'POC_HOST', 'POC_PORT', 'POC_SCHEMA', 'POC_USER', 'POC_PASSWORD',
    'POC_AI_HOST', 'POC_AI_PORT', 'POC_AI_SCHEMA', 'POC_AI_USER',
    'POC_AI_PASSWORD'] as $key) {
    if (empty($processEnv[$key])) throw new RuntimeException('AI DB context missing');
    putenv($key . '=' . $processEnv[$key]);
}
define('TP_ENV', 'poc');
define('BUSINESS', 'aizhct');
define('ENTERPRISE_NO', '10001');
require $root . '/vendor/autoload.php';
(new \think\App($root))->setEnvName('poc')->initialize();
\cores\BaseModel::$storeId = 10001;
$dsn = 'dm:host=' . getenv('POC_AI_HOST') . ';port=' . getenv('POC_AI_PORT')
    . ';schema=' . getenv('POC_AI_SCHEMA');
$db = new PDO($dsn, getenv('POC_AI_USER'), getenv('POC_AI_PASSWORD'),
    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$id = (int)$db->query('SELECT ID FROM YOSHOP_DISHES'
    . ' WHERE STORE_ID=10001 AND IS_DELETE=0 ORDER BY ID DESC LIMIT 1')->fetchColumn();
if ($id <= 0) throw new RuntimeException('No read-only dish ID available');
$results = [];
$stages = [[], ['cate'], ['cate', 'file'], ['cate', 'file', 'unsuitable'],
    ['cate', 'file', 'unsuitable', 'foods'],
    ['cate', 'file', 'unsuitable', 'foods', 'tag'], ['foods']];
foreach ($stages as $relations) {
    $label = $relations === [] ? 'base' : implode('+', $relations);
    try {
        $model = (new \app\store\model\dishes\Dishes())
            ->with($relations)->where(['id' => $id, 'is_delete' => 0])->find();
        $results[$label] = ['ok' => $model !== null];
    } catch (Throwable $error) {
        $details = method_exists($error, 'getData') ? (array)$error->getData() : [];
        $pdoInfo = (array)($details['PDO Error Info'] ?? []);
        $driverMessage = (string)($pdoInfo['Driver Error Message'] ?? $error->getMessage());
        $sql = (string)($details['Database Status']['Error SQL'] ?? '');
        $errorKind = 'other';
        foreach (['ambiguous' => '/ambig|歧义|不明确/i',
            'missing_identifier' => '/invalid.*(column|identifier)|unknown column|无效.*(列|标识)|列.*不存在/i',
            'syntax' => '/syntax|语法|解析错误|SQL语句/i',
            'datatype' => '/data type|类型|转换|convert/i'] as $kind => $pattern) {
            if (preg_match($pattern, $driverMessage)) { $errorKind = $kind; break; }
        }
        $results[$label] = [
            'ok' => false,
            'class' => get_class($error),
            'code' => (string)$error->getCode(),
            'sqlstate' => (string)($pdoInfo['SQLSTATE'] ?? ''),
            'driver_code' => (string)($pdoInfo['Driver Error Code'] ?? ''),
            'driver_error_kind' => $errorKind,
            'sql_features' => [
                'join' => (bool)preg_match('/\\bJOIN\\b/i', $sql),
                'pivot_alias' => (bool)preg_match('/\\bpivot\\b/i', $sql),
                'pivot_field_alias' => strpos($sql, 'pivot__') !== false,
                'cast' => (bool)preg_match('/\\bCAST\\b/i', $sql),
                'quoted_identifier' => strpos($sql, '"') !== false,
                'has_foods' => stripos($sql, 'yoshop_foods') !== false,
                'has_dishes_foods' => stripos($sql, 'yoshop_dishes_foods') !== false,
            ],
        ];
    }
}
$aliasChecks = [];
foreach (['bare_pivot' => 'SELECT pivot.DISHES_ID FROM YOSHOP_DISHES_FOODS pivot WHERE 1=0',
    'quoted_pivot' => 'SELECT "pivot".DISHES_ID FROM YOSHOP_DISHES_FOODS "pivot" WHERE 1=0']
    as $label => $sql) {
    try {
        $db->query($sql);
        $aliasChecks[$label] = ['ok' => true];
    } catch (Throwable $error) {
        $aliasChecks[$label] = ['ok' => false, 'class' => get_class($error),
            'code' => (string)$error->getCode()];
    }
}
echo json_encode(['mode' => 'read-only-existing-id-redacted', 'results' => $results,
    'zero_row_alias_checks' => $aliasChecks],
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES) . PHP_EOL;
