
import os

path = "src/generation/CrystalSpiresGenerator.js"
with open(path, "r", encoding="utf-8") as f:
    lines = f.readlines()

# Locate connectVerticalLevels
start_idx = -1
for i, line in enumerate(lines):
    if "connectVerticalLevels(spires) {" in line:
        start_idx = i
        break

if start_idx == -1:
    print("Error: connectVerticalLevels not found")
    exit(1)

# Inject logs UNCOMMENTED
new_code = """  connectVerticalLevels(spires) {
    console.log("Running connectVerticalLevels...");
    spires.forEach((s, sIdx) => {
      const sortedPlats = [...s.platforms].sort((a, b) => a.y - b.y);
      console.log(`Spire ${sIdx} has ${sortedPlats.length} platforms.`);

      for (let i = 0; i < sortedPlats.length - 1; i++) {
        const pA = sortedPlats[i];
        const pB = sortedPlats[i + 1];

        const dy = pB.y - pA.y;
        console.log(`Spire ${sIdx} Pair ${i}->${i+1}: dy=${dy}`);
        
        if (dy > 18) {
             console.log("  Skipped: Too far");
             continue; 
        }

        const angleA = this.rng.next() * Math.PI * 2;
        const angleB = angleA + Math.PI * 0.66; // 120 deg

        const rA = pA.radius - 0.5; // Inset slightly
        const rB = pB.radius - 0.5;

        const start = {
          x: pA.x + Math.cos(angleA) * rA,
          y: pA.y,
          z: pA.z + Math.sin(angleA) * rA,
        };

        const end = {
          x: pB.x + Math.cos(angleB) * rB,
          y: pB.y,
          z: pB.z + Math.sin(angleB) * rB,
        };

        const success = this.buildBridge(start, end, { x: s.x, z: s.z }, 0.0);
        console.log(`  BuildBridge Result: ${success}`);

        if (success) {
          pA.connections.push(start);
          pB.connections.push(end);
          this.generatedAssets.bridges.push({
            fromSpire: sIdx, 
            toSpire: sIdx, // Same Spire
            fromPlatIdx: s.platforms.indexOf(pA),
            toPlatIdx: s.platforms.indexOf(pB),
            start,
            end,
          });
        }
      }
    });
  }
"""

end_idx = -1
for i in range(start_idx+1, len(lines)):
    if "connectSpires(spires) {" in lines[i]:
        end_idx = i - 1
        break

final_lines = lines[:start_idx] + [new_code] + lines[end_idx+1:] 

with open(path, "w", encoding="utf-8") as f:
    f.writelines(final_lines)

print("Debug Instrumentation Complete")
