import{world as e,BlockPermutation as t}from"@minecraft/server";let Direction=Object.freeze({NORTH:"north",SOUTH:"south",EAST:"east",WEST:"west"});export class StructureSpawner{constructor(){this.registeredStructures=[],e.afterEvents.playerPlaceBlock.subscribe(this.handleBlockPlacement.bind(this))}registerStructure({pattern:t,anchor:r,flat:i,spawnWeight:n}){if(!t||!r){e.sendMessage("[StructureSpawner] Registration error: pattern, anchor, and spawnEntityTypeId are required.");return}if(r.row<0||r.row>=t.length||!t[r.row]||r.col<0||r.col>=t[r.row].length){e.sendMessage("[StructureSpawner] Registration error: Anchor coordinates are invalid for the pattern.");return}let o=t[r.row][r.col];if(!o){e.sendMessage("[StructureSpawner] Registration error: The anchor block in the pattern cannot be empty.");return}this.registeredStructures.push({pattern:t,anchor:r,triggerBlockTypeId:o,flat:i,spawnWeight:n})}handleBlockPlacement(e){let r=e.block;for(let i of this.registeredStructures){let n=r.dimension;if(r.typeId!==i.triggerBlockTypeId)continue;let o=i.pattern,a=i.anchor.row,c=i.anchor.col,s=o.length,l=o[0].length;for(let u of Object.values(Direction)){let h=!0,f=[];for(let g=0;g<s;g++){for(let p=0;p<l;p++){let d=o[g][p];""===d&&(d="minecraft:air");let S=0,w=0,m=a-g;switch(u){case Direction.NORTH:w=p-c;break;case Direction.SOUTH:w=c-p;break;case Direction.WEST:S=p-c;break;case Direction.EAST:S=c-p}if(i.flat){switch(u){case Direction.NORTH:w=-(w=p-c),S=-m;break;case Direction.SOUTH:w=-(w=c-p),S=m;break;case Direction.WEST:S=-(S=p-c),w=m;break;case Direction.EAST:S=-(S=c-p),w=-m}m=0}let k={x:r.location.x+S,y:r.location.y+m,z:r.location.z+w},y=n.getBlock(k);if(!y||y.typeId!==d){h=!1;break}f.push(y)}if(!h)break}if(h){f.forEach(e=>{let r=n.getBlock(e.location)?.permutation;r&&!r.matches("minecraft:air")&&e.setPermutation(t.resolve("minecraft:air"))});let T={x:r.location.x,y:r.location.y-(i.flat?-1:i.pattern.length-1-a),z:r.location.z};try{n.spawnEntity(this.getRandomEntity(i.spawnWeight),T)}catch(b){console.error(`[StructureSpawner] Failed to summon entity ${i.spawnWeight}: ${b}`)}return}}}}getRandomEntity(e){let t=e.reduce((e,t)=>e+t.weight,0),r=Math.random()*t,i=0;for(let n of e)if(r<(i+=n.weight))return n.id}}