<?php

declare(strict_types=1);

// Read only the declared type of dishes.weight; never select business rows.
if ($argc!==2 || !in_array($argv[1],
    ['--mysql-local-weight-meta','--dm-c-weight-meta'],true)) {
    fwrite(STDERR,"Explicit read-only weight metadata flag required\n");
    exit(2);
}
$lane=$argv[1]==='--mysql-local-weight-meta'?'A/B MySQL':'C DM';
try {
    if ($lane==='A/B MySQL') {
        $load=static function(string $file): array { return require $file; };
        $local=$load('/workspace/zhct/zhctproject/store/application/config/local/database.php');
        foreach (['/tmp/zhct-http-store-a.l5omH8',
            '/tmp/zhct-http-store-mysql.dQTTBP'] as $root) {
            $runtime=$load($root.'/application/database.php');
            foreach (['hostname','database','username','password'] as $field) {
                if (!isset($local[$field],$runtime[$field])
                    || $local[$field]!==$runtime[$field]) {
                    throw new RuntimeException('Not code-local development MySQL');
                }
            }
        }
        $db=new PDO('mysql:host='.$local['hostname'].';port='.
            (int)($local['hostport']??3306).';dbname='.$local['database']
            .';charset=utf8mb4',(string)$local['username'],
            (string)$local['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.')!==0) {
            throw new RuntimeException('Not MySQL5.6');
        }
        $stmt=$db->prepare('SELECT DATA_TYPE,COLUMN_TYPE,NUMERIC_PRECISION,'
            .' NUMERIC_SCALE,IS_NULLABLE FROM information_schema.COLUMNS'
            .' WHERE TABLE_SCHEMA=? AND TABLE_NAME=? AND COLUMN_NAME=?');
        $stmt->execute([(string)$local['database'],'ydy_dishes','weight']);
        $row=$stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) throw new RuntimeException('MySQL weight column absent');
        $result=[
            'declared_type'=>strtolower((string)$row['DATA_TYPE']),
            'column_type'=>strtolower((string)$row['COLUMN_TYPE']),
            'precision'=>$row['NUMERIC_PRECISION']===null?null:
                (int)$row['NUMERIC_PRECISION'],
            'scale'=>$row['NUMERIC_SCALE']===null?null:
                (int)$row['NUMERIC_SCALE'],
            'nullable'=>$row['IS_NULLABLE']==='YES',
        ];
    } else {
        $pid=(string)getenv('POC_RUNTIME_PID');
        $root='/tmp/zhct-dm-poc-20260928.fcpiiN/store';
        if ($pid!=='112175' || strpos((string)file_get_contents(
            '/proc/'.$pid.'/cmdline'),$root.'/public')===false) {
            throw new RuntimeException('Wrong C Store 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) {
            $parts=explode('=',$entry,2);
            if (count($parts)===2 && array_key_exists($parts[0],$env)) {
                $env[$parts[0]]=$parts[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('Wrong C nonproduction DB');
        }
        $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,
            ]);
        if (strtoupper((string)$db->query(
            "SELECT SYS_CONTEXT('USERENV','CURRENT_SCHEMA') FROM DUAL")
            ->fetchColumn())!=='ZHCT_APP') {
            throw new RuntimeException('Wrong C schema');
        }
        $stmt=$db->prepare('SELECT DATA_TYPE,DATA_PRECISION,DATA_SCALE,NULLABLE'
            .' FROM USER_TAB_COLUMNS WHERE TABLE_NAME=? AND COLUMN_NAME=?');
        $stmt->execute(['YDY_DISHES','WEIGHT']);
        $row=$stmt->fetch(PDO::FETCH_ASSOC);
        if (!$row) throw new RuntimeException('C weight column absent');
        $row=array_change_key_case($row,CASE_LOWER);
        $result=[
            'declared_type'=>(string)$row['data_type'],
            'precision'=>$row['data_precision']===null?null:
                (int)$row['data_precision'],
            'scale'=>$row['data_scale']===null?null:
                (int)$row['data_scale'],
            'nullable'=>(string)$row['nullable']==='Y',
        ];
    }
    echo json_encode(['lane'=>$lane,'table'=>'dishes','column'=>'weight',
        'metadata'=>$result],JSON_UNESCAPED_SLASHES).PHP_EOL;
} catch (Throwable $error) {
    echo json_encode(['status'=>'blocked','lane'=>$lane,
        'class'=>get_class($error),
        'code'=>(string)$error->getCode()],JSON_UNESCAPED_SLASHES).PHP_EOL;
    exit(1);
}
