<?php
require __DIR__.'/common.php';$final=json_decode(file_get_contents(__DIR__.'/private/phase-candidate-final.json'),true);$own=$final['own'];
$product=$q('SELECT uuid,name FROM ydy_nutrition WHERE uuid=?',[$own['product_uuid']]);$template=$q('SELECT uuid,name FROM ydy_nutrition_template WHERE uuid=?',[$own['template_uuid']]);if(($product[0]['name']??'')!=='CDXNF11F5-candidate-product'||($template[0]['name']??'')!=='CDXNF11F5-candidate-template')throw new RuntimeException('Exact candidate ownership');
$cols=['power','carbohydrate','protein','fat','sodium'];$aggregates=['COUNT(*) AS own_n'];foreach($cols as $f){$aggregates[]='SUM('.$f.') AS '.$f.'_sum';$aggregates[]='AVG('.$f.') AS '.$f.'_avg';}$sql='SELECT '.implode(',',$aggregates).' FROM (SELECT '.implode(',',$cols).' FROM ydy_nutrition WHERE uuid=? UNION ALL SELECT '.implode(',',$cols).' FROM ydy_nutrition_template WHERE uuid=?) own_nutrients';$rows=$q($sql,[$own['product_uuid'],$own['template_uuid']]);$bits=[];foreach($rows[0]as $k=>$v)$bits[$k]=['value'=>$v,'type'=>gettype($v),'bits64'=>is_float($v)?bin2hex(pack('d',$v)):null];if((int)$rows[0]['own_n']!==2)throw new RuntimeException('Exactly2 own original rows');$save('aggregate-read.json',['lane'=>$lane,'scope'=>$own,'rows'=>$rows,'native'=>$bits,'oracle'=>$GLOBALS['NF_ORACLE'],'business_DML'=>0,'DDL'=>0,'HTTP'=>0]);echo json_encode(['lane'=>$lane,'SELECT'=>3,'own_rows'=>2,'SQL_writes'=>0,'HTTP'=>0]),"\n";
