import { expect } from "@esm-bundle/chai";
import { VoxelGrid } from "../../src/grid/VoxelGrid.js";
import { CaveGenerator } from "../../src/generation/CaveGenerator.js";
import { RuinGenerator } from "../../src/generation/RuinGenerator.js";

describe("System: Procedural Generation", () => {
  let grid;

  beforeEach(() => {
    grid = new VoxelGrid(20, 10, 20); // Small test map
  });

  describe("Cave Generator (Organic)", () => {
    it("CoA 1: Should modify the grid from empty state", () => {
      const gen = new CaveGenerator(grid, 12345); // Fixed seed
      gen.generate(0.5, 1); // 50% fill, 1 pass

      // Check if grid is no longer all 0s
      let solidCount = 0;
      for (let i = 0; i < grid.cells.length; i++) {
        if (grid.cells[i] !== 0) solidCount++;
      }

      expect(solidCount).to.be.greaterThan(0);
    });

    it("CoA 2: Should keep borders solid (Containment)", () => {
      const gen = new CaveGenerator(grid, 12345);
      gen.generate();

      // Check coordinate 0,0,0 (Corner)
      expect(grid.isSolid({ x: 0, y: 0, z: 0 })).to.be.true;
      // Check coordinate 19,0,19 (Opposite Corner)
      expect(grid.isSolid({ x: 19, y: 0, z: 19 })).to.be.true;
    });
  });

  describe("Ruin Generator (Structural)", () => {
    it("CoA 3: Should generate clear rooms", () => {
      // Fill with solid first to verify carving
      grid.fill(1);

      const gen = new RuinGenerator(grid, 12345);
      gen.generate(3, 4, 6); // 3 rooms, size 4-6

      // There should be AIR (0) voxels now
      let airCount = 0;
      for (let i = 0; i < grid.cells.length; i++) {
        if (grid.cells[i] === 0) airCount++;
      }

      expect(airCount).to.be.greaterThan(0);
    });

    it.skip("CoA 4: Rooms should have walkable floors", () => {
      const gen = new RuinGenerator(grid, 12345);
      gen.generate(1, 5, 5); // 1 room

      // Find an air tile
      let roomTile = null;
      for (let x = 0; x < 20; x++) {
        for (let z = 0; z < 20; z++) {
          // Check level 1 (where rooms are carved)
          if (grid.getCell(x, 1, z) === 0) {
            roomTile = { x, y: 1, z };
            break;
          }
        }
        if (roomTile) break;
      }

      expect(roomTile).to.not.be.null;

      // The tile BELOW the air should be solid
      const floor = grid.getCell(roomTile.x, roomTile.y - 1, roomTile.z);
      expect(floor).to.not.equal(0);
    });
  });
});
