<?php
declare(strict_types=1);

// Metadata only. No business-row SELECT, HTTP, cache, DDL or DML.
$stage = 'start';
set_exception_handler(static function (Throwable $error) use (&$stage): void {
    echo json_encode(['status' => 'redacted_error', 'stage' => $stage,
        'class' => get_class($error)]), PHP_EOL;
    exit(2);
});

$target = (string)getenv('CDX_CATALOG_META_TARGET');
if ($target === 'B') {
    $stage = 'local_config';
    $path = '/Users/wiscourper/Documents/workspace/zhct/zhctproject/ai_api/.env.local';
    if (realpath($path) !== $path) throw new RuntimeException('Unexpected local config path');
    $ini = parse_ini_file($path, true, INI_SCANNER_RAW);
    $part = is_array($ini) ? ($ini['DATABASE'] ?? null) : null;
    if (!is_array($part) || ($part['TYPE'] ?? '') !== 'mysql') {
        throw new RuntimeException('Not the code-local MySQL development connection');
    }
    $schema = (string)$part['DATABASE'];
    if ($schema !== 'ai_zhct') throw new RuntimeException('Unexpected development schema');
    $pdo = new PDO('mysql:host=' . $part['HOSTNAME'] . ';port=' . $part['HOSTPORT']
        . ';dbname=' . $schema . ';charset=utf8', $part['USERNAME'], $part['PASSWORD'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_TIMEOUT => 5,
            PDO::ATTR_CASE => PDO::CASE_LOWER]);
    if ((string)$pdo->query('SELECT DATABASE()')->fetchColumn() !== $schema
        || strpos((string)$pdo->query('SELECT VERSION()')->fetchColumn(), '5.6.') !== 0) {
        throw new RuntimeException('Development database identity mismatch');
    }
    $sql = 'SELECT COLUMN_NAME, DATA_TYPE, NUMERIC_PRECISION AS P, '
        . 'NUMERIC_SCALE AS S, IS_NULLABLE AS N '
        . 'FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_SCHEMA=? AND TABLE_NAME=? '
        . 'ORDER BY ORDINAL_POSITION';
    $tables = ['yoshop_dishes', 'yoshop_foods', 'yoshop_dishes_foods'];
} elseif ($target === 'C') {
    $stage = 'nonproduction_runtime';
    $pid = 53772;
    $root = '/tmp/zhct-ai-http-20260929.3XDj3w';
    $command = file_get_contents('/proc/' . $pid . '/cmdline');
    if (!is_string($command) || strpos($command, $root . '/public') === false
        || strpos($command, '127.0.0.1:18102') === false) {
        throw new RuntimeException('C isolated process changed');
    }
    $raw = file_get_contents('/proc/' . $pid . '/environ');
    if (!is_string($raw)) throw new RuntimeException('C isolated 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);
    }
    foreach (['POC_DIALECT' => 'dm', 'POC_EXTERNAL_STUBS' => '1',
        'POC_AI_HOST' => '127.0.0.1', 'POC_AI_PORT' => '5238',
        'POC_AI_SCHEMA' => 'AIZHCT_APP'] as $name => $expected) {
        if (($config[$name] ?? null) !== $expected) {
            throw new RuntimeException('C AI database boundary changed');
        }
    }
    if (empty($config['POC_AI_USER']) || empty($config['POC_AI_PASSWORD'])) {
        throw new RuntimeException('C business account unavailable');
    }
    $pdo = new PDO('dm:host=127.0.0.1;port=5238;schema=AIZHCT_APP',
        $config['POC_AI_USER'], $config['POC_AI_PASSWORD'],
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
            PDO::ATTR_CASE => PDO::CASE_LOWER]);
    $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 !== 'AIZHCT_APP' || $schema !== 'AIZHCT_APP') {
        throw new RuntimeException('C user/schema identity changed');
    }
    $sql = 'SELECT COLUMN_NAME, DATA_TYPE, DATA_PRECISION AS P, '
        . 'DATA_SCALE AS S, NULLABLE AS N '
        . 'FROM USER_TAB_COLUMNS WHERE TABLE_NAME=? ORDER BY COLUMN_ID';
    $tables = ['YOSHOP_DISHES', 'YOSHOP_FOODS', 'YOSHOP_DISHES_FOODS'];
} else {
    throw new RuntimeException('Explicit B/C target required');
}

$stage = 'numeric_column_metadata';
$results = [];
$stmt = $pdo->prepare($sql);
foreach ($tables as $table) {
    $bind = $target === 'B' ? [$schema, $table] : [$table];
    $stmt->execute($bind);
    $rows = $stmt->fetchAll(PDO::FETCH_ASSOC);
    if (!$rows) throw new RuntimeException('Missing table metadata');
    $numeric = [];
    foreach ($rows as $row) {
        $type = strtoupper((string)$row['data_type']);
        if (!in_array($type, ['DECIMAL', 'NUMERIC', 'DEC', 'NUMBER',
            'FLOAT', 'DOUBLE'], true)) continue;
        $numeric[] = ['name' => strtoupper((string)$row['column_name']),
            'type' => $type,
            'precision' => $row['p'] === null ? null : (int)$row['p'],
            'scale' => $row['s'] === null ? null : (int)$row['s'],
            'nullable' => strtoupper((string)$row['n'])];
    }
    $results[$table] = ['total_columns' => count($rows),
        'numeric_columns' => $numeric];
}
echo json_encode(['status' => 'read_only_metadata', 'target' => $target,
    'tables' => $results, 'business_rows_read' => 0, 'writes' => 0],
    JSON_UNESCAPED_SLASHES), PHP_EOL;
