<?php

declare(strict_types=1);

// Read-only shape of one previously hashed A/B dish/food row; no values output.
try {
    $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 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 engine');
    }
    $pairs=$db->query('SELECT DISTINCT d.uuid D_UUID,f.id F_ID'
        .' FROM ydy_dishes d JOIN ydy_dish c ON c.dishes_uuid=d.uuid'
        .' JOIN ydy_foods_composition f ON f.id=c.composition_id'
        .' WHERE d.status=1 AND d.is_del=1 AND d.store_id=10001')
        ->fetchAll(PDO::FETCH_ASSOC);
    $dishUuid='';
    $foodId=0;
    foreach ($pairs as $pair) {
        if (substr(hash('sha256',(string)$pair['D_UUID']),0,12)==='af3250f90a91'
            && substr(hash('sha256',(string)$pair['F_ID']),0,12)==='c17edaae86e4') {
            $dishUuid=(string)$pair['D_UUID'];
            $foodId=(int)$pair['F_ID'];
            break;
        }
    }
    if ($dishUuid==='' || $foodId<=0) {
        throw new RuntimeException('Original anonymous row not found');
    }
    $out=['source_hash_matched'=>true,'tables'=>[]];
    foreach (['ydy_dishes'=>['uuid',$dishUuid],
        'ydy_foods_composition'=>['id',$foodId]] as $table=>$target) {
        $stmt=$db->prepare('SELECT COLUMN_NAME,NUMERIC_SCALE FROM '
            .'information_schema.COLUMNS WHERE TABLE_SCHEMA=?'
            .' AND TABLE_NAME=? AND DATA_TYPE=? ORDER BY ORDINAL_POSITION');
        $stmt->execute([$config['database'],$table,'decimal']);
        $columns=$stmt->fetchAll(PDO::FETCH_ASSOC);
        if (!$columns) throw new RuntimeException('DECIMAL metadata absent');
        $names=[];
        foreach ($columns as $column) {
            $name=(string)$column['COLUMN_NAME'];
            if (!preg_match('/^[a-z_][a-z0-9_]*$/',$name)) {
                throw new RuntimeException('Unexpected decimal column identifier');
            }
            $names[]=$name;
        }
        $query=$db->prepare('SELECT '.implode(',',$names).' FROM '.$table
            .' WHERE '.$target[0].'=?');
        $query->execute([$target[1]]);
        $rows=$query->fetchAll(PDO::FETCH_ASSOC);
        if (count($rows)!==1) throw new RuntimeException('Anonymous row not unique');
        $types=[];
        $formats=[];
        $scaleDist=[];
        foreach ($columns as $column) {
            $name=(string)$column['COLUMN_NAME'];
            $scale=(int)$column['NUMERIC_SCALE'];
            $type=gettype($rows[0][$name]);
            $types[$type]=($types[$type]??0)+1;
            $scaleDist[$scale]=($scaleDist[$scale]??0)+1;
            $format=is_string($rows[0][$name])
                && preg_match('/^-?\d+\.\d{2}$/',$rows[0][$name])
                ? 'signed_digits.fixed_2'
                : ($type==='NULL'?'NULL':'other');
            $formats[$format]=($formats[$format]??0)+1;
        }
        $examples=[];
        foreach (['weight','energy','protein','carbohydrate','dietary_fiber'] as $name) {
            if (!array_key_exists($name,$rows[0])) continue;
            $value=$rows[0][$name];
            $examples[$name]=['type'=>gettype($value),
                'shape'=>is_string($value)
                    && preg_match('/^-?\d+\.\d{2}$/',$value)
                    ?'digits.2dp':(gettype($value)==='NULL'?'NULL':'other')];
        }
        $out['tables'][$table]=['decimal_columns'=>count($columns),
            'declared_scale_distribution'=>$scaleDist,
            'php_type_counts'=>$types,'value_shape_counts'=>$formats,
            'representative_shapes'=>$examples];
    }
    echo json_encode($out,JSON_UNESCAPED_SLASHES).PHP_EOL;
} catch (Throwable $error) {
    echo json_encode(['status'=>'error','class'=>get_class($error),
        'code'=>$error->getCode()]).PHP_EOL;
    exit(1);
}
