import { recordInBasicBlock } from './ir_cfg.js';
import { getNodeDataFromID, getOrCreateNode } from './ir_dag.js';
import { NodeType } from './ir_types.js';
import './strands_FES.js';

function createPhiNode(strandsContext, phiInputs, varName) {
  // Determine the proper dimension and baseType from the inputs
  const validInputs = phiInputs.filter(input => input.value.id !== null);
  if (validInputs.length === 0) {
    throw new Error(`No valid inputs for phi node for variable ${varName}`);
  }
  // Get dimension and baseType from first valid input
  let firstInput = validInputs
    .map((input) => getNodeDataFromID(strandsContext.dag, input.value.id))
    .find((input) => input.dimension) ??
      getNodeDataFromID(strandsContext.dag, validInputs[0].value.id);
  const dimension = firstInput.dimension;
  const baseType = firstInput.baseType;
  const nodeData = {
    nodeType: NodeType.PHI,
    dimension,
    baseType,
    dependsOn: phiInputs.map(input => input.value.id).filter(id => id !== null),
    phiBlocks: phiInputs.map(input => input.blockId)};
  const id = getOrCreateNode(strandsContext.dag, nodeData);
  recordInBasicBlock(strandsContext.cfg, strandsContext.cfg.currentBlock, id);
  return {
    id,
    dimension,
    baseType
  };
}

export { createPhiNode };
