<?php

declare(strict_types=1);

// Read-only actual DDL for the eight residual Cater/find component keys.
$lane=(string)getenv('CDX_NESTED_DIALECT');
$fields=['composition_ratio','dishes_ssb','foods_ratio','foods_weight',
    'gia','gib','raw_flag_weight','ssb'];
try {
    if ($lane==='mysql') {
        $path=realpath(__DIR__
            . '/../../../../../zhctproject/store/application/config/local/database.php');
        if (!$path || strpos($path,
            '/zhctproject/store/application/config/local/')===false) {
            throw new RuntimeException('Approved local DB config absent');
        }
        $load=static function(string $file): array { return require $file; };
        $config=$load($path);
        $db=new PDO('mysql:host='.$config['hostname'].';port='
            .(int)($config['hostport']??3306).';dbname='
            .$config['database'].';charset=utf8mb4',
            (string)$config['username'],(string)$config['password'],[
                PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_EMULATE_PREPARES=>false,
                PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,
                PDO::ATTR_TIMEOUT=>8,
            ]);
        if (strpos((string)$db->query('SELECT VERSION()')->fetchColumn(),'5.6.')===false) {
            throw new RuntimeException('Unexpected MySQL engine');
        }
        $in=implode(',',array_fill(0,count($fields),'?'));
        $sql='SELECT COLUMN_NAME,DATA_TYPE,COLUMN_TYPE,NUMERIC_PRECISION,'
            .'NUMERIC_SCALE,IS_NULLABLE FROM information_schema.COLUMNS'
            .' WHERE TABLE_SCHEMA=? AND TABLE_NAME=?'
            .' AND COLUMN_NAME IN ('.$in.') ORDER BY COLUMN_NAME';
        $stmt=$db->prepare($sql);
        $stmt->execute(array_merge([$config['database'],'ydy_dish'],$fields));
    } elseif ($lane==='dm') {
        $pid=(string)getenv('POC_RUNTIME_PID');
        $cmdline=ctype_digit($pid)
            ?(string)file_get_contents('/proc/'.$pid.'/cmdline'):'';
        if (!ctype_digit($pid)
            || strpos($cmdline,'127.0.0.1:18080')===false
            || strpos($cmdline,
                '/tmp/zhct-dm-poc-20260928.fcpiiN/store/public')===false) {
            throw new RuntimeException('Unexpected C runtime');
        }
        $env=array_fill_keys(['POC_HOST','POC_PORT','POC_SCHEMA',
            'POC_USER','POC_PASSWORD'],'');
        foreach (explode("\0",(string)file_get_contents('/proc/'.$pid.'/environ')) as $entry) {
            $pair=explode('=',$entry,2);
            if (count($pair)===2 && array_key_exists($pair[0],$env)) {
                $env[$pair[0]]=$pair[1];
            }
        }
        if ($env['POC_HOST']!=='127.0.0.1' || $env['POC_PORT']!=='5237'
            || strtoupper($env['POC_SCHEMA'])!=='ZHCT_APP'
            || strtoupper($env['POC_USER'])!=='ZHCT_APP'
            || $env['POC_PASSWORD']==='') {
            throw new RuntimeException('Unexpected C database');
        }
        $db=new PDO('dm:host=127.0.0.1;port=5237;schema=ZHCT_APP',
            $env['POC_USER'],$env['POC_PASSWORD'],[
                PDO::ATTR_ERRMODE=>PDO::ERRMODE_EXCEPTION,
                PDO::ATTR_DEFAULT_FETCH_MODE=>PDO::FETCH_ASSOC,
            ]);
        $in=implode(',',array_fill(0,count($fields),'?'));
        $sql='SELECT COLUMN_NAME,DATA_TYPE,DATA_PRECISION,DATA_SCALE,'
            .'NULLABLE FROM USER_TAB_COLUMNS WHERE TABLE_NAME=?'
            .' AND COLUMN_NAME IN ('.$in.') ORDER BY COLUMN_NAME';
        $stmt=$db->prepare($sql);
        $stmt->execute(array_merge(['YDY_DISH'],array_map('strtoupper',$fields)));
    } else {
        throw new RuntimeException('Choose approved mysql or dm');
    }
    $rows=$stmt->fetchAll(PDO::FETCH_ASSOC);
    if (count($rows)!==count($fields)) {
        throw new RuntimeException('Nested component column count changed');
    }
    echo json_encode(['lane'=>$lane,'columns'=>$rows],
        JSON_UNESCAPED_SLASHES).PHP_EOL;
} catch (Throwable $error) {
    echo json_encode(['status'=>'error','class'=>get_class($error),
        'code'=>$error->getCode()]).PHP_EOL;
    exit(1);
}
