All files / src/runtime spike-scratch-importer.ts

53.34% Statements 367/688
40.7% Branches 46/113
71.42% Functions 5/7
53.34% Lines 367/688

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 7851x                                         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x             1x       1x                                                                                                                                                       1x   3x 19x 19x 19x 19x 19x 16x 16x 16x   3x     3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 3x 3x     3x 3x 3x 3x   3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 3x 12x 12x 12x   12x 12x 12x 12x 12x 12x 12x 12x 12x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 2x 2x   3x 1x 1x   3x 1x 1x   3x       3x 3x   3x   3x 3x 3x 3x 3x 3x 3x   1x 15x 15x 15x 15x 15x 15x 15x 15x 15x 15x   15x 15x     15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 15x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 14x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 13x                                 11x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 11x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 10x                           8x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     8x 1x 1x 1x 1x 1x 1x 1x   1x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 7x                               6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 6x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     5x                       4x                           4x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x                         2x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                         1x                           1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x     1x                                                                             15x 15x   1x 3x 3x 3x 3x 3x 3x 3x 3x         3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x       3x 3x   1x 1x 1x 1x 1x 1x       1x 1x 1x       1x 1x 1x   1x       1x       1x       1x       1x       1x     1x 1x 1x 1x 1x 1x 1x 1x 1x 1x                       1x   1x                                                                                                                                                             1x 22x 22x 22x 22x 22x                     22x 22x 1x  
import JSZip from 'jszip';
 
export interface VisualBlock {
  id: string;
  opcode: string;
  category: 'event' | 'movement' | 'motor' | 'control' | 'sensor' | 'operator' | 'variable' | 'light' | 'sound' | 'myblock';
  icon: string;
  label: string;
  params: Record<string, string>;
  colorHex: string;
  children?: VisualBlock[];
  elseChildren?: VisualBlock[];
}
 
export interface SpikeScratchImportResult {
  projectName: string;
  pythonCode: string;
  visualBlocks: VisualBlock[];
  totalBlocks: number;
}
 
const COLOR_MAP: Record<string, string> = {
  '-1': 'none',
  '': 'none',
  '0': 'black',
  '1': 'magenta',
  '2': 'purple',
  '3': 'blue',
  '4': 'azure',
  '5': 'green',
  '7': 'yellow',
  '8': 'orange',
  '9': 'red',
  '10': 'white',
};
 
/**
 * High-Fidelity Scratch / Word Blocks Importer for LEGO SPIKE Prime App projects (.llsp3, .llsp, .sb3, .json).
 * Unpacks the project archive, parses the Scratch 3.0 AST, and transpiles the block sequence
 * into standard, fully executable SPIKE Prime Python code, with an accompanying visual block structure.
 */
export class SpikeScratchImporter {
  /**
   * Parses a SPIKE app project file (.llsp3, .llsp, .sb3, or raw Scratch JSON)
   */
  public static async importProject(
    fileData: ArrayBuffer | Blob | string,
    defaultName: string = 'Imported SPIKE Program'
  ): Promise<SpikeScratchImportResult> {
    let projectJson: any;
    let projectName = defaultName.replace(/\.(llsp3?|sb3|json)$/i, '');
 
    if (typeof fileData === 'string' && fileData.trim().startsWith('{')) {
      projectJson = JSON.parse(fileData);
    } else {
      const zip = new JSZip();
      const zipContent = await zip.loadAsync(fileData as any);
 
      // 1. Try reading manifest.json for authentic project metadata
      const manifestFile = zipContent.file('manifest.json');
      if (manifestFile) {
        try {
          const manifestText = await manifestFile.async('text');
          const manifest = JSON.parse(manifestText);
          if (manifest.name) {
            projectName = manifest.name;
          }
        } catch (_) {}
      }
 
      // 2. Check for nested scratch.sb3 (SPIKE 3 .llsp3 format)
      const sb3File = zipContent.file('scratch.sb3');
      if (sb3File) {
        const sb3Buffer = await sb3File.async('arraybuffer');
        const nestedZip = new JSZip();
        const nestedContent = await nestedZip.loadAsync(sb3Buffer);
        const innerProj = nestedContent.file('project.json');
        if (!innerProj) {
          throw new Error('No project.json found inside scratch.sb3 archive');
        }
        const text = await innerProj.async('text');
        projectJson = JSON.parse(text);
      } else {
        // 3. Check for direct project.json or projectbody.json (SPIKE 2 .llsp or Scratch .sb3 format)
        const projFile =
          zipContent.file('projectbody.json') ||
          zipContent.file('project.json') ||
          zipContent.file('model.json');
 
        if (projFile) {
          const text = await projFile.async('text');
          projectJson = JSON.parse(text);
        } else {
          // Look for any .json file in the archive
          const allJson = Object.keys(zipContent.files).find((k) => k.endsWith('.json') && !k.endsWith('manifest.json'));
          if (allJson) {
            const text = await zipContent.file(allJson)!.async('text');
            projectJson = JSON.parse(text);
          } else {
            throw new Error('Unsupported project archive: no project.json or scratch.sb3 found');
          }
        }
      }
    }
 
    // 4. Locate blocks dictionary from target sprite/actor
    let blocks: Record<string, any> = {};
    if (projectJson.targets && Array.isArray(projectJson.targets)) {
      // Find non-stage target with active blocks, or fallback to first target
      const actor = projectJson.targets.find((t: any) => !t.isStage && t.blocks && Object.keys(t.blocks).length > 0) || projectJson.targets[0];
      blocks = actor?.blocks || {};
    } else if (projectJson.blocks) {
      blocks = projectJson.blocks;
    }
 
    return this.transpileBlocks(blocks, projectName);
  }
 
  /**
   * Traverses Scratch blocks AST starting from hat blocks and generates Python + visual descriptors
   */
  public static transpileBlocks(blocks: Record<string, any>, projectName: string): SpikeScratchImportResult {
    // Collect all top-level hat blocks (when program starts)
    const hatIds = Object.keys(blocks).filter((id) => {
      const b = blocks[id];
      if (!b || typeof b !== 'object') return false;
      const op = b.opcode || '';
      return (
        b.topLevel ||
        op.includes('whenProgramStarts') ||
        op.includes('whenflagclicked') ||
        op.includes('start_hat')
      );
    });
 
    // Devices discovered during block parsing
    const devices = {
      hasHub: false,
      hasMotors: false,
      motorPairPorts: ['A', 'B'] as [string, string],
      individualMotors: new Set<string>(),
      colorSensors: new Set<string>(),
      distanceSensors: new Set<string>(),
      hasTimer: false,
    };
 
    const pyBodyLines: string[] = [];
    const visualBlocks: VisualBlock[] = [];
    let totalBlockCount = 0;
 
    // Traverse starting from primary hat block
    const primaryHatId = hatIds.find((id) => {
      const op = blocks[id]?.opcode || '';
      return op.includes('whenProgramStarts') || op.includes('whenflagclicked');
    }) || hatIds[0];
 
    if (primaryHatId) {
      totalBlockCount++;
      visualBlocks.push({
        id: primaryHatId,
        opcode: blocks[primaryHatId].opcode,
        category: 'event',
        icon: '🚩',
        label: 'When Program Starts',
        params: {},
        colorHex: '#eab308',
      });
 
      let currId = blocks[primaryHatId].next;
      while (currId) {
        const b = blocks[currId];
        if (!b) break;
        totalBlockCount++;
 
        const res = this.processBlock(currId, b, blocks, devices, 0);
        if (res.pyLines.length > 0) {
          pyBodyLines.push(...res.pyLines);
        }
        if (res.visualBlock) {
          visualBlocks.push(res.visualBlock);
        }
        currId = b.next;
      }
    }
 
    // Build standard SPIKE Prime Python header with all discovered sensors & motors
    const headerLines: string[] = [
      '# -------------------------------------------------------------------------',
      `# Translated from SPIKE App Word Blocks: "${projectName}"`,
      '# -------------------------------------------------------------------------',
      'from spike import PrimeHub, Motor, MotorPair, ColorSensor, DistanceSensor',
      'from spike.control import wait_for_seconds, wait_until',
      '',
      'hub = PrimeHub()',
    ];
 
    if (devices.hasMotors || pyBodyLines.some((l) => l.includes('motors.'))) {
      headerLines.push(`motors = MotorPair('${devices.motorPairPorts[0]}', '${devices.motorPairPorts[1]}')`);
    }
 
    for (const p of Array.from(devices.individualMotors).sort()) {
      headerLines.push(`motor_${p.toLowerCase()} = Motor('${p}')`);
    }
 
    for (const p of Array.from(devices.colorSensors).sort()) {
      headerLines.push(`color_${p.toLowerCase()} = ColorSensor('${p}')`);
    }
 
    for (const p of Array.from(devices.distanceSensors).sort()) {
      headerLines.push(`dist_${p.toLowerCase()} = DistanceSensor('${p}')`);
    }
 
    headerLines.push('');
    headerLines.push('# --- Main Program ---');
 
    const fullPythonCode = [...headerLines, ...(pyBodyLines.length > 0 ? pyBodyLines : ['pass'])].join('\n') + '\n';
 
    return {
      projectName,
      pythonCode: fullPythonCode,
      visualBlocks,
      totalBlocks: totalBlockCount,
    };
  }
 
  private static processBlock(
    bid: string,
    b: any,
    blocks: Record<string, any>,
    devices: any,
    indentDepth: number
  ): { pyLines: string[]; visualBlock?: VisualBlock } {
    const indent = '    '.repeat(indentDepth);
    const op = b.opcode || '';
    const inputs = b.inputs || {};
    const fields = b.fields || {};
 
    const pyLines: string[] = [];
    let visualBlock: VisualBlock | undefined;
 
    // 1. MOVEMENT BLOCKS (Blue)
    if (op === 'flippermove_setMovementPair' || op === 'spike_setMovementPair') {
      devices.hasMotors = true;
      const pair = this.resolveInput(inputs.PAIR, blocks) || 'AB';
      const p1 = pair[0] || 'A';
      const p2 = pair[1] || 'B';
      devices.motorPairPorts = [p1, p2];
      pyLines.push(`${indent}motors = MotorPair('${p1}', '${p2}')`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'movement',
        icon: 'πŸš—',
        label: `Set movement motors to [${p1}+${p2}]`,
        params: { left: p1, right: p2 },
        colorHex: '#0284c7',
      };
    } else if (op === 'flippermove_movementSpeed' || op === 'spike_movementSpeed') {
      devices.hasMotors = true;
      const spd = this.resolveInput(inputs.SPEED, blocks) || '50';
      pyLines.push(`${indent}motors.set_default_speed(${spd})`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'movement',
        icon: '⚑',
        label: `Set movement speed to [${spd}%]`,
        params: { speed: spd },
        colorHex: '#0284c7',
      };
    } else if (op === 'flippermove_move' || op === 'spike_move') {
      devices.hasMotors = true;
      const dir = this.resolveInput(inputs.DIRECTION, blocks) || 'forward';
      const val = this.resolveInput(inputs.VALUE, blocks) || '10';
      const unit = (fields.UNIT && fields.UNIT[0]) || 'cm';
      const numVal = parseFloat(val) || 0;
      const finalVal = dir === 'back' ? -Math.abs(numVal) : Math.abs(numVal);
      pyLines.push(`${indent}motors.move(${finalVal}, '${unit}')`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'movement',
        icon: dir === 'back' ? '⬇️' : '⬆️',
        label: `Move [${dir}] for [${val}] [${unit}]`,
        params: { direction: dir, value: val, unit },
        colorHex: '#0284c7',
      };
    } else if (op === 'flippermove_startMove' || op === 'spike_startMove') {
      devices.hasMotors = true;
      const dir = this.resolveInput(inputs.DIRECTION, blocks) || 'forward';
      if (dir === 'back') {
        pyLines.push(`${indent}motors.start(0, -50)`);
      } else {
        pyLines.push(`${indent}motors.start()`);
      }
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'movement',
        icon: '▢️',
        label: `Start moving [${dir}]`,
        params: { direction: dir },
        colorHex: '#0284c7',
      };
    } else if (op === 'flippermove_startSteer' || op === 'spike_startSteer') {
      devices.hasMotors = true;
      const steering = this.resolveInput(inputs.STEERING, blocks) || '0';
      const speed = this.resolveInput(inputs.SPEED, blocks) || '50';
      pyLines.push(`${indent}motors.start(${steering}, ${speed})`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'movement',
        icon: 'πŸ”„',
        label: `Start steering [${steering}] at [${speed}%]`,
        params: { steering, speed },
        colorHex: '#0284c7',
      };
    } else if (op === 'flippermove_stopMove' || op === 'spike_stopMove') {
      devices.hasMotors = true;
      pyLines.push(`${indent}motors.stop()`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'movement',
        icon: '⏹️',
        label: 'Stop moving',
        params: {},
        colorHex: '#0284c7',
      };
    } else if (op === 'flippermoremove_startDualSpeed' || op === 'spike_startDualSpeed') {
      devices.hasMotors = true;
      const l = this.resolveInput(inputs.LEFT, blocks) || '0';
      const r = this.resolveInput(inputs.RIGHT, blocks) || '0';
      pyLines.push(`${indent}motors.start_tank(${l}, ${r})`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'movement',
        icon: 'πŸŽ›οΈ',
        label: `Start moving tank Left: [${l}%], Right: [${r}%]`,
        params: { left: l, right: r },
        colorHex: '#0284c7',
      };
    } else if (op === 'flippermoremove_moveDualSpeed' || op === 'spike_moveDualSpeed') {
      devices.hasMotors = true;
      const l = this.resolveInput(inputs.LEFT, blocks) || '0';
      const r = this.resolveInput(inputs.RIGHT, blocks) || '0';
      const val = this.resolveInput(inputs.VALUE, blocks) || '1';
      const unit = (fields.UNIT && fields.UNIT[0]) || 'rotations';
      pyLines.push(`${indent}motors.move_tank(${val}, '${unit}', ${l}, ${r})`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'movement',
        icon: 'πŸŽ›οΈ',
        label: `Move tank for [${val}] [${unit}] Left: [${l}%], Right: [${r}%]`,
        params: { value: val, unit, left: l, right: r },
        colorHex: '#0284c7',
      };
 
    // 2. INDIVIDUAL MOTOR BLOCKS (Cyan / Teal)
    } else if (op === 'flippermotor_motorTurnForDirection' || op === 'spike_motorTurnForDirection') {
      const port = this.resolveInput(inputs.PORT, blocks) || 'A';
      devices.individualMotors.add(port);
      const dir = this.resolveInput(inputs.DIRECTION, blocks) || 'clockwise';
      const val = this.resolveInput(inputs.VALUE, blocks) || '1';
      const unit = (fields.UNIT && fields.UNIT[0]) || 'rotations';
      const numVal = parseFloat(val) || 0;
      const sign = dir === 'counterclockwise' ? -1 : 1;
 
      if (unit === 'rotations') {
        pyLines.push(`${indent}motor_${port.toLowerCase()}.run_for_degrees(${numVal * 360 * sign})`);
      } else if (unit === 'degrees') {
        pyLines.push(`${indent}motor_${port.toLowerCase()}.run_for_degrees(${numVal * sign})`);
      } else {
        pyLines.push(`${indent}motor_${port.toLowerCase()}.run_for_seconds(${numVal})`);
      }
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'motor',
        icon: 'βš™οΈ',
        label: `Turn Motor [Port ${port}] [${dir}] for [${val}] [${unit}]`,
        params: { port, direction: dir, value: val, unit },
        colorHex: '#06b6d4',
      };
    } else if (op === 'flippermotor_motorStartDirection' || op === 'spike_motorStartDirection') {
      const port = this.resolveInput(inputs.PORT, blocks) || 'A';
      devices.individualMotors.add(port);
      const dir = this.resolveInput(inputs.DIRECTION, blocks) || 'clockwise';
      const speed = this.resolveInput(inputs.SPEED, blocks) || '50';
      const sign = dir === 'counterclockwise' ? '-' : '';
      pyLines.push(`${indent}motor_${port.toLowerCase()}.start(${sign}${speed})`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'motor',
        icon: 'βš™οΈ',
        label: `Start Motor [Port ${port}] [${dir}] at [${speed}%]`,
        params: { port, direction: dir, speed },
        colorHex: '#06b6d4',
      };
    } else if (op === 'flippermotor_motorStop' || op === 'spike_motorStop') {
      const port = this.resolveInput(inputs.PORT, blocks) || 'A';
      devices.individualMotors.add(port);
      pyLines.push(`${indent}motor_${port.toLowerCase()}.stop()`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'motor',
        icon: '⏹️',
        label: `Stop Motor [Port ${port}]`,
        params: { port },
        colorHex: '#06b6d4',
      };
    } else if (op === 'flippermotor_motorSetSpeed' || op === 'spike_motorSetSpeed') {
      const port = this.resolveInput(inputs.PORT, blocks) || 'A';
      devices.individualMotors.add(port);
      const spd = this.resolveInput(inputs.SPEED, blocks) || '50';
      pyLines.push(`${indent}motor_${port.toLowerCase()}.set_default_speed(${spd})`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'motor',
        icon: '⚑',
        label: `Set Motor [Port ${port}] speed to [${spd}%]`,
        params: { port, speed: spd },
        colorHex: '#06b6d4',
      };
 
    // 3. SENSORS (Purple)
    } else if (op === 'flippersensors_resetYaw' || op === 'spike_resetYaw') {
      devices.hasHub = true;
      pyLines.push(`${indent}hub.motion_sensor.reset_yaw_angle()`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'sensor',
        icon: '🧭',
        label: 'Reset Yaw angle to 0Β°',
        params: {},
        colorHex: '#a855f7',
      };
    } else if (op === 'flippersensors_resetTimer' || op === 'sensing_resettimer') {
      devices.hasTimer = true;
      pyLines.push(`${indent}timer.reset()`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'sensor',
        icon: '⏱️',
        label: 'Reset Timer',
        params: {},
        colorHex: '#a855f7',
      };
 
    // 4. CONTROL BLOCKS (Orange)
    } else if (op === 'control_wait') {
      const secs = this.resolveInput(inputs.DURATION, blocks) || '1';
      pyLines.push(`${indent}wait_for_seconds(${secs})`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'control',
        icon: '⏳',
        label: `Wait [${secs}] seconds`,
        params: { duration: secs },
        colorHex: '#f97316',
      };
    } else if (op === 'control_wait_until') {
      const cond = this.resolveCondition(inputs.CONDITION, blocks, devices);
      pyLines.push(`${indent}while not (${cond.pyExpr}):`);
      pyLines.push(`${indent}    wait_for_seconds(0.01)`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'control',
        icon: '⏳',
        label: `Wait until <${cond.label}>`,
        params: { condition: cond.label },
        colorHex: '#f97316',
      };
    } else if (op === 'control_repeat') {
      const times = this.resolveInput(inputs.TIMES, blocks) || '10';
      pyLines.push(`${indent}for _ in range(${times}):`);
      const children = this.processSubstack(inputs.SUBSTACK, blocks, devices, indentDepth + 1, pyLines);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'control',
        icon: 'πŸ”',
        label: `Repeat [${times}] times`,
        params: { times },
        colorHex: '#f97316',
        children,
      };
    } else if (op === 'control_forever') {
      pyLines.push(`${indent}while True:`);
      const children = this.processSubstack(inputs.SUBSTACK, blocks, devices, indentDepth + 1, pyLines);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'control',
        icon: '♾️',
        label: 'Forever',
        params: {},
        colorHex: '#f97316',
        children,
      };
    } else if (op === 'control_if') {
      const cond = this.resolveCondition(inputs.CONDITION, blocks, devices);
      pyLines.push(`${indent}if ${cond.pyExpr}:`);
      const children = this.processSubstack(inputs.SUBSTACK, blocks, devices, indentDepth + 1, pyLines);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'control',
        icon: '❓',
        label: `If <${cond.label}> then`,
        params: { condition: cond.label },
        colorHex: '#f97316',
        children,
      };
    } else if (op === 'control_if_else') {
      const cond = this.resolveCondition(inputs.CONDITION, blocks, devices);
      pyLines.push(`${indent}if ${cond.pyExpr}:`);
      const children = this.processSubstack(inputs.SUBSTACK, blocks, devices, indentDepth + 1, pyLines);
      pyLines.push(`${indent}else:`);
      const elseChildren = this.processSubstack(inputs.SUBSTACK2, blocks, devices, indentDepth + 1, pyLines);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'control',
        icon: '❓',
        label: `If <${cond.label}> then ... else`,
        params: { condition: cond.label },
        colorHex: '#f97316',
        children,
        elseChildren,
      };
 
    // 5. VARIABLES / DATA (Orange / Red)
    } else if (op === 'data_setvariableto') {
      const varName = (fields.VARIABLE && fields.VARIABLE[0]) || 'var';
      const val = this.resolveInput(inputs.VALUE, blocks) || '0';
      pyLines.push(`${indent}${varName} = ${val}`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'variable',
        icon: 'πŸ“¦',
        label: `Set [${varName}] to [${val}]`,
        params: { variable: varName, value: val },
        colorHex: '#ea580c',
      };
    } else if (op === 'data_changevariableby') {
      const varName = (fields.VARIABLE && fields.VARIABLE[0]) || 'var';
      const val = this.resolveInput(inputs.VALUE, blocks) || '1';
      pyLines.push(`${indent}${varName} += ${val}`);
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'variable',
        icon: 'πŸ“¦',
        label: `Change [${varName}] by [${val}]`,
        params: { variable: varName, value: val },
        colorHex: '#ea580c',
      };
    } else {
      // Generic fallback for unhandled custom block
      visualBlock = {
        id: bid,
        opcode: op,
        category: 'control',
        icon: '🧩',
        label: `${op.replace(/^[a-z]+_/, '')}`,
        params: {},
        colorHex: '#64748b',
      };
    }
 
    return { pyLines, visualBlock };
  }
 
  private static processSubstack(
    substackInput: any,
    blocks: Record<string, any>,
    devices: any,
    indentDepth: number,
    targetPyLines: string[]
  ): VisualBlock[] {
    const children: VisualBlock[] = [];
    if (!substackInput) {
      targetPyLines.push('    '.repeat(indentDepth) + 'pass');
      return children;
    }
 
    let currId = substackInput[1];
    let addedAny = false;
    while (currId) {
      const b = blocks[currId];
      if (!b) break;
      const res = this.processBlock(currId, b, blocks, devices, indentDepth);
      if (res.pyLines.length > 0) {
        targetPyLines.push(...res.pyLines);
        addedAny = true;
      }
      if (res.visualBlock) {
        children.push(res.visualBlock);
      }
      currId = b.next;
    }
 
    if (!addedAny) {
      targetPyLines.push('    '.repeat(indentDepth) + 'pass');
    }
 
    return children;
  }
 
  private static resolveCondition(
    condInput: any,
    blocks: Record<string, any>,
    devices: any
  ): { pyExpr: string; label: string } {
    if (!condInput || !condInput[1]) {
      return { pyExpr: 'False', label: 'false' };
    }
 
    const bId = condInput[1];
    const b = blocks[bId];
    if (!b) {
      return { pyExpr: String(bId), label: String(bId) };
    }
 
    const op = b.opcode || '';
    const inputs = b.inputs || {};
    const fields = b.fields || {};
 
    if (op === 'operator_lt') {
      const l = this.resolveExpression(inputs.OPERAND1, blocks, devices);
      const r = this.resolveExpression(inputs.OPERAND2, blocks, devices);
      return { pyExpr: `${l.pyExpr} < ${r.pyExpr}`, label: `${l.label} < ${r.label}` };
    } else if (op === 'operator_gt') {
      const l = this.resolveExpression(inputs.OPERAND1, blocks, devices);
      const r = this.resolveExpression(inputs.OPERAND2, blocks, devices);
      return { pyExpr: `${l.pyExpr} > ${r.pyExpr}`, label: `${l.label} > ${r.label}` };
    } else if (op === 'operator_equals') {
      const l = this.resolveExpression(inputs.OPERAND1, blocks, devices);
      const r = this.resolveExpression(inputs.OPERAND2, blocks, devices);
      return { pyExpr: `${l.pyExpr} == ${r.pyExpr}`, label: `${l.label} = ${r.label}` };
    } else if (op === 'operator_and') {
      const l = this.resolveCondition(inputs.OPERAND1, blocks, devices);
      const r = this.resolveCondition(inputs.OPERAND2, blocks, devices);
      return { pyExpr: `(${l.pyExpr} and ${r.pyExpr})`, label: `(${l.label} and ${r.label})` };
    } else if (op === 'operator_or') {
      const l = this.resolveCondition(inputs.OPERAND1, blocks, devices);
      const r = this.resolveCondition(inputs.OPERAND2, blocks, devices);
      return { pyExpr: `(${l.pyExpr} or ${r.pyExpr})`, label: `(${l.label} or ${r.label})` };
    } else if (op === 'operator_not') {
      const c = this.resolveCondition(inputs.OPERAND, blocks, devices);
      return { pyExpr: `not (${c.pyExpr})`, label: `not (${c.label})` };
    } else if (op === 'flippersensors_isColor' || op === 'spike_isColor') {
      const port = this.resolveInput(inputs.PORT, blocks) || 'B';
      devices.colorSensors.add(port);
      const rawColor = this.resolveInput(inputs.VALUE, blocks) || '0';
      const colorName = COLOR_MAP[rawColor] || rawColor;
      return {
        pyExpr: `color_${port.toLowerCase()}.get_color() == '${colorName}'`,
        label: `Color Sensor [Port ${port}] is [${colorName}]`,
      };
    } else if (op === 'flippersensors_isDistance' || op === 'spike_isDistance') {
      const port = this.resolveInput(inputs.PORT, blocks) || 'E';
      devices.distanceSensors.add(port);
      const val = this.resolveInput(inputs.VALUE, blocks) || '20';
      const comparison = (fields.COMPARISON && fields.COMPARISON[0]) || '<';
      return {
        pyExpr: `dist_${port.toLowerCase()}.get_distance_cm() ${comparison} ${val}`,
        label: `Distance Sensor [Port ${port}] ${comparison} ${val} cm`,
      };
    }
 
    return { pyExpr: 'True', label: 'true' };
  }
 
  private static resolveExpression(
    exprInput: any,
    blocks: Record<string, any>,
    devices: any
  ): { pyExpr: string; label: string } {
    if (!exprInput) return { pyExpr: '0', label: '0' };
    const val = exprInput[1];
 
    if (Array.isArray(val)) {
      return { pyExpr: String(val[1]), label: String(val[1]) };
    }
 
    if (typeof val === 'string') {
      const b = blocks[val];
      if (!b) return { pyExpr: val, label: val };
      const op = b.opcode || '';
      const inputs = b.inputs || {};
      const fields = b.fields || {};
 
      if (op === 'flippersensors_orientationAxis' || op === 'spike_orientationAxis') {
        devices.hasHub = true;
        const axis = (fields.AXIS && fields.AXIS[0]) || 'yaw';
        return {
          pyExpr: `hub.motion_sensor.get_${axis}_angle()`,
          label: `${axis.toUpperCase()} Angle`,
        };
      } else if (op === 'flippersensors_colorReflectedLight') {
        const port = this.resolveInput(inputs.PORT, blocks) || 'C';
        devices.colorSensors.add(port);
        return {
          pyExpr: `color_${port.toLowerCase()}.get_reflected_light()`,
          label: `Reflected Light on [Port ${port}]`,
        };
      } else if (op === 'flippersensors_distance') {
        const port = this.resolveInput(inputs.PORT, blocks) || 'E';
        devices.distanceSensors.add(port);
        return {
          pyExpr: `dist_${port.toLowerCase()}.get_distance_cm()`,
          label: `Distance on [Port ${port}]`,
        };
      } else if (op === 'flippermotor_absolutePosition') {
        const port = this.resolveInput(inputs.PORT, blocks) || 'A';
        devices.individualMotors.add(port);
        return {
          pyExpr: `motor_${port.toLowerCase()}.get_position()`,
          label: `Position of Motor [Port ${port}]`,
        };
      } else if (op === 'operator_add') {
        const l = this.resolveExpression(inputs.NUM1, blocks, devices);
        const r = this.resolveExpression(inputs.NUM2, blocks, devices);
        return { pyExpr: `(${l.pyExpr} + ${r.pyExpr})`, label: `(${l.label} + ${r.label})` };
      } else if (op === 'operator_subtract') {
        const l = this.resolveExpression(inputs.NUM1, blocks, devices);
        const r = this.resolveExpression(inputs.NUM2, blocks, devices);
        return { pyExpr: `(${l.pyExpr} - ${r.pyExpr})`, label: `(${l.label} - ${r.label})` };
      } else if (op === 'operator_multiply') {
        const l = this.resolveExpression(inputs.NUM1, blocks, devices);
        const r = this.resolveExpression(inputs.NUM2, blocks, devices);
        return { pyExpr: `(${l.pyExpr} * ${r.pyExpr})`, label: `(${l.label} * ${r.label})` };
      } else if (op === 'operator_divide') {
        const l = this.resolveExpression(inputs.NUM1, blocks, devices);
        const r = this.resolveExpression(inputs.NUM2, blocks, devices);
        return { pyExpr: `(${l.pyExpr} / ${r.pyExpr})`, label: `(${l.label} / ${r.label})` };
      } else if (op === 'data_variable') {
        const varName = (fields.VARIABLE && fields.VARIABLE[0]) || 'var';
        return { pyExpr: varName, label: varName };
      }
 
      // Check fields of shadow block
      for (const fv of Object.values(fields)) {
        if (Array.isArray(fv) && fv.length > 0) {
          return { pyExpr: String(fv[0]), label: String(fv[0]) };
        }
      }
    }
 
    return { pyExpr: String(val), label: String(val) };
  }
 
  private static resolveInput(inputTuple: any, blocks: Record<string, any>): string {
    if (!inputTuple) return '';
    const val = inputTuple[1];
    if (Array.isArray(val)) {
      return String(val[1]);
    }
    if (typeof val === 'string') {
      const targetB = blocks[val];
      if (!targetB) return val;
      const fields = targetB.fields || {};
      for (const fv of Object.values(fields)) {
        if (Array.isArray(fv) && fv.length > 0) {
          return String(fv[0]);
        }
      }
    }
    return String(val || '');
  }
}