import json
import multiprocessing
import random
from tqdm import tqdm

# Define ship configurations
ships = {"Carrier": 5, "Battleship": 4, "Cruiser": 3, "Submarine": 3, "Destroyer": 2}


def place_ships(grid_size=100):
    """Randomly place ships on a grid ensuring fair use of all cells."""
    grid = [""] * grid_size
    positions = list(range(grid_size))

    for ship, size in ships.items():
        placed = False
        while not placed:
            start = random.choice(positions)
            orientation = random.choice(["horizontal", "vertical"])
            if orientation == "horizontal" and start % 10 + size <= 10:
                if all(grid[start + i] == "" for i in range(size)):
                    for i in range(size):
                        grid[start + i] = ship
                    placed = True
            elif orientation == "vertical" and start // 10 + size <= 10:
                if all(grid[start + i * 10] == "" for i in range(size)):
                    for i in range(size):
                        grid[start + i * 10] = ship
                    placed = True
    return grid


def worker(num_boards, output_queue):
    """Worker function to generate boards."""
    for _ in range(num_boards):
        board = place_ships()
        output_queue.put(board)


def main(total_boards=1000000, num_processes=4):
    """Main function to manage multiprocessing and progress tracking."""
    boards_per_process = total_boards // num_processes
    output_queue = multiprocessing.Queue()
    processes = []

    for _ in range(num_processes):
        p = multiprocessing.Process(
            target=worker, args=(boards_per_process, output_queue)
        )
        processes.append(p)
        p.start()

    with open("battleship_boards.json", "w") as f:
        for _ in tqdm(range(total_boards), desc="Generating Boards"):
            board = output_queue.get()
            json.dump(board, f)
            f.write("\n")

    for p in processes:
        p.join()


if __name__ == "__main__":
    main()
