#!/bin/bash
# maze_generator.sh

if [ $# -ne 2 ]; then
    echo "Usage: $0 <width> <height>"
    echo "Example: $0 10 10"
    exit 1
fi

WIDTH=$1
HEIGHT=$2
FILENAME="maze${WIDTH}x${HEIGHT}.txt"

# Create empty maze with all walls
declare -A maze
for ((y=0; y<HEIGHT; y++)); do
    for ((x=0; x<WIDTH; x++)); do
        maze[$y,$x]="#"
    done
done

# Set start at (1,1)
START_X=1
START_Y=1
maze[$START_Y,$START_X]="S"

# Random walk to create path
CURRENT_X=$START_X
CURRENT_Y=$START_Y
STEPS=$((WIDTH * HEIGHT / 3))

for ((i=0; i<STEPS; i++)); do
    DIR=$((RANDOM % 4))
    NEW_X=$CURRENT_X
    NEW_Y=$CURRENT_Y
    
    case $DIR in
        0) NEW_X=$((CURRENT_X + 1)) ;;
        1) NEW_X=$((CURRENT_X - 1)) ;;
        2) NEW_Y=$((CURRENT_Y + 1)) ;;
        3) NEW_Y=$((CURRENT_Y - 1)) ;;
    esac
    
    if [ $NEW_X -gt 0 ] && [ $NEW_X -lt $((WIDTH-1)) ] && [ $NEW_Y -gt 0 ] && [ $NEW_Y -lt $((HEIGHT-1)) ]; then
        if [ "${maze[$NEW_Y,$NEW_X]}" != "S" ]; then
            maze[$NEW_Y,$NEW_X]=" "
            CURRENT_X=$NEW_X
            CURRENT_Y=$NEW_Y
        fi
    fi
done

# Set exit at final position (ensure not same as start)
maze[$CURRENT_Y,$CURRENT_X]="E"

# Ensure exit is different from start
if [ $CURRENT_X -eq $START_X ] && [ $CURRENT_Y -eq $START_Y ]; then
    if [ $((START_Y+1)) -lt $((HEIGHT-1)) ]; then
        maze[$((START_Y+1)),$START_X]="E"
        maze[$START_Y,$START_X]="S"
    else
        maze[$START_Y,$((START_X+1))]="E"
    fi
fi

# Write to file
> $FILENAME
for ((y=0; y<HEIGHT; y++)); do
    line=""
    for ((x=0; x<WIDTH; x++)); do
        line="${line}${maze[$y,$x]}"
    done
    echo "$line" >> $FILENAME
done

echo "Maze saved to $FILENAME"
echo "Start at (1,1), Exit at ($CURRENT_X,$CURRENT_Y)"
