import * as Blockly from 'blockly';
import { ROBOT_TEMPLATE_LIST, normalizeFieldValues } from './robotComponents.js';

/**
 * @param {Blockly.Block} block
 * @param {string} inputName
 * @returns {number | null}
 */
function getConnectedMathNumber(block, inputName) {
  const inp = block.getInput(inputName);
  const child = inp?.connection?.targetBlock();
  if (child && child.type === 'math_number') {
    const n = Number(child.getFieldValue('NUM'));
    return Number.isFinite(n) ? n : null;
  }
  return null;
}

/**
 * Scan the workspace for supported init / sonar blocks and build component rows.
 *
 * @param {Blockly.Workspace} workspace
 * @returns {{ kind: string, fields: Record<string, string> }[]}
 */
export function importRobotFromWorkspace(workspace) {
  /** @type {{ kind: string, fields: Record<string, string> }[]} */
  const components = [];

  for (const tmpl of ROBOT_TEMPLATE_LIST) {
    if (tmpl.applyAs === 'statement') {
      const blocks = workspace.getBlocksByType(tmpl.blockType, false);
      for (const b of blocks) {
        /** @type {Record<string, unknown>} */
        const raw = {};
        for (const f of tmpl.fields) {
          if (b.getField(f.key)) {
            raw[f.key] = b.getFieldValue(f.key);
          }
        }
        components.push({
          kind: tmpl.id,
          fields: normalizeFieldValues(tmpl.id, raw),
        });
      }
    } else if (tmpl.applyAs === 'sonar_reporter') {
      const blocks = workspace.getBlocksByType(tmpl.blockType, false);
      for (const b of blocks) {
        const trig = getConnectedMathNumber(b, 'TRIG');
        const echo = getConnectedMathNumber(b, 'ECHO');
        if (trig != null && echo != null) {
          components.push({
            kind: tmpl.id,
            fields: normalizeFieldValues(tmpl.id, { TRIG: trig, ECHO: echo }),
          });
        }
      }
    }
  }

  return components;
}
