--- Day 15: Warehouse Woes ---

You appear back inside your own mini submarine! Each Historian drives their mini submarine in a different direction; maybe the Chief has his own submarine down here somewhere as well?

You look up to see a vast school of lanternfish swimming past you. On closer inspection, they seem quite anxious, so you drive your mini submarine over to see if you can help.

Because lanternfish populations grow rapidly, they need a lot of food, and that food needs to be stored somewhere. That's why these lanternfish have built elaborate warehouse complexes operated by robots!

These lanternfish seem so anxious because they have lost control of the robot that operates one of their most important warehouses! It is currently running amok, pushing around boxes in the warehouse with no regard for lanternfish logistics or lanternfish inventory management strategies.

Right now, none of the lanternfish are brave enough to swim up to an unpredictable robot so they could shut it off. However, if you could anticipate the robot's movements, maybe they could find a safe option.

The lanternfish already have a map of the warehouse and a list of movements the robot will attempt to make (your puzzle input). The problem is that the movements will sometimes fail as boxes are shifted around, making the actual movements of the robot difficult to predict.

For example:

##########
#..O..O.O#
#......O.#
#.OO..O.O#
#..O@..O.#
#O#..O...#
#O..O..O.#
#.OO.O.OO#
#....O...#
##########

<vv>^<v^>v>^vv^v>v<>v^v<v<^vv<<<^><<><>>v<vvv<>^v^>^<<<><<v<<<v^vv^v>^
vvv<<^>^v^^><<>>><>^<<><^vv^^<>vvv<>><^^v>^>vv<>v<<<<v<^v>^<^^>>>^<v<v
><>vv>v^v^<>><>>>><^^>vv>v<^^^>>v^v^<^^>v^^>v^<^v>v<>>v^v^<v>v^^<^^vv<
<<v<^>>^^^^>>>v^<>vvv^><v<<<>^^^vv^<vvv>^>v<^^^^v<>^>vvvv><>>v^<<^^^^^
^><^><>>><>^^<<^^v>>><^<v>^<vv>>v>>>^v><>^v><<<<v>>v<v<v>vvv>^<><<>^><
^>><>^v<><^vvv<^^<><v<<<<<><^v<<<><<<^^<v<^^^><^>>^<v^><<<^>>^v<v^v<v^
>^>>^v>vv>^<<^v<>><<><<v<<v><>v<^vv<<<>^^v^>^^>>><<^v>>v^v><^^>>^<>vv^
<><^^>^^^<><vvvvv^v<v<<>^v<v>v<<^><<><<><<<^^<<<^<<>><<><^^^>^^<>^>v<>
^^>vv<^v^v<vv>^<><v<^v>^^^>>>^^vvv^>vvv<>>>^<^>>>>>^<<^v>^vvv<>^<><<v>
v^^>>><<^^<>>^v^<v^vv<>v^<<>^<^v^v><^<<<><<^<v><v<>vv>>v><v^<vv<>v^<<^
As the robot (@) attempts to move, if there are any boxes (O) in the way, the robot will also attempt to push those boxes. However, if this action would cause the robot or a box to move into a wall (#), nothing moves instead, including the robot. The initial positions of these are shown on the map at the top of the document the lanternfish gave you.

The rest of the document describes the moves (^ for up, v for down, < for left, > for right) that the robot will attempt to make, in order. (The moves form a single giant sequence; they are broken into multiple lines just to make copy-pasting easier. Newlines within the move sequence should be ignored.)

Here is a smaller example to get started:

########
#..O.O.#
##@.O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

<^^>>>vv<v>>v<<
Were the robot to attempt the given sequence of moves, it would push around the boxes as follows:

Initial state:
########
#..O.O.#
##@.O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move <:
########
#..O.O.#
##@.O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move ^:
########
#.@O.O.#
##..O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move ^:
########
#.@O.O.#
##..O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move >:
########
#..@OO.#
##..O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move >:
########
#...@OO#
##..O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move >:
########
#...@OO#
##..O..#
#...O..#
#.#.O..#
#...O..#
#......#
########

Move v:
########
#....OO#
##..@..#
#...O..#
#.#.O..#
#...O..#
#...O..#
########

Move v:
########
#....OO#
##..@..#
#...O..#
#.#.O..#
#...O..#
#...O..#
########

Move <:
########
#....OO#
##.@...#
#...O..#
#.#.O..#
#...O..#
#...O..#
########

Move v:
########
#....OO#
##.....#
#..@O..#
#.#.O..#
#...O..#
#...O..#
########

Move >:
########
#....OO#
##.....#
#...@O.#
#.#.O..#
#...O..#
#...O..#
########

Move >:
########
#....OO#
##.....#
#....@O#
#.#.O..#
#...O..#
#...O..#
########

Move v:
########
#....OO#
##.....#
#.....O#
#.#.O@.#
#...O..#
#...O..#
########

Move <:
########
#....OO#
##.....#
#.....O#
#.#O@..#
#...O..#
#...O..#
########

Move <:
########
#....OO#
##.....#
#.....O#
#.#O@..#
#...O..#
#...O..#
########
The larger example has many more moves; after the robot has finished those moves, the warehouse would look like this:

##########
#.O.O.OOO#
#........#
#OO......#
#OO@.....#
#O#.....O#
#O.....OO#
#O.....OO#
#OO....OO#
##########
The lanternfish use their own custom Goods Positioning System (GPS for short) to track the locations of the boxes. The GPS coordinate of a box is equal to 100 times its distance from the top edge of the map plus its distance from the left edge of the map. (This process does not stop at wall tiles; measure all the way to the edges of the map.)

So, the box shown below has a distance of 1 from the top edge of the map and 4 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 4 = 104.

#######
#...O..
#......
The lanternfish would like to know the sum of all boxes' GPS coordinates after the robot finishes moving. In the larger example, the sum of all boxes' GPS coordinates is 10092. In the smaller example, the sum is 2028.

Predict the motion of the robot and boxes in the warehouse. After the robot is finished moving, what is the sum of all boxes' GPS coordinates?

Your puzzle answer was 1499739.

--- Part Two ---

The lanternfish use your information to find a safe moment to swim in and turn off the malfunctioning robot! Just as they start preparing a festival in your honor, reports start coming in that a second warehouse's robot is also malfunctioning.

This warehouse's layout is surprisingly similar to the one you just helped. There is one key difference: everything except the robot is twice as wide! The robot's list of movements doesn't change.

To get the wider warehouse's map, start with your original map and, for each tile, make the following changes:

If the tile is #, the new map contains ## instead.
If the tile is O, the new map contains [] instead.
If the tile is ., the new map contains .. instead.
If the tile is @, the new map contains @. instead.
This will produce a new warehouse map which is twice as wide and with wide boxes that are represented by []. (The robot does not change size.)

The larger example from before would now look like this:

####################
##....[]....[]..[]##
##............[]..##
##..[][]....[]..[]##
##....[]@.....[]..##
##[]##....[]......##
##[]....[]....[]..##
##..[][]..[]..[][]##
##........[]......##
####################
Because boxes are now twice as wide but the robot is still the same size and speed, boxes can be aligned such that they directly push two other boxes at once. For example, consider this situation:

#######
#...#.#
#.....#
#..OO@#
#..O..#
#.....#
#######

<vv<<^^<<^^
After appropriately resizing this map, the robot would push around these boxes as follows:

Initial state:
##############
##......##..##
##..........##
##....[][]@.##
##....[]....##
##..........##
##############

Move <:
##############
##......##..##
##..........##
##...[][]@..##
##....[]....##
##..........##
##############

Move v:
##############
##......##..##
##..........##
##...[][]...##
##....[].@..##
##..........##
##############

Move v:
##############
##......##..##
##..........##
##...[][]...##
##....[]....##
##.......@..##
##############

Move <:
##############
##......##..##
##..........##
##...[][]...##
##....[]....##
##......@...##
##############

Move <:
##############
##......##..##
##..........##
##...[][]...##
##....[]....##
##.....@....##
##############

Move ^:
##############
##......##..##
##...[][]...##
##....[]....##
##.....@....##
##..........##
##############

Move ^:
##############
##......##..##
##...[][]...##
##....[]....##
##.....@....##
##..........##
##############

Move <:
##############
##......##..##
##...[][]...##
##....[]....##
##....@.....##
##..........##
##############

Move <:
##############
##......##..##
##...[][]...##
##....[]....##
##...@......##
##..........##
##############

Move ^:
##############
##......##..##
##...[][]...##
##...@[]....##
##..........##
##..........##
##############

Move ^:
##############
##...[].##..##
##...@.[]...##
##....[]....##
##..........##
##..........##
##############
This warehouse also uses GPS to locate the boxes. For these larger boxes, distances are measured from the edge of the map to the closest edge of the box in question. So, the box shown below has a distance of 1 from the top edge of the map and 5 from the left edge of the map, resulting in a GPS coordinate of 100 * 1 + 5 = 105.

##########
##...[]...
##........
In the scaled-up version of the larger example from above, after the robot has finished all of its moves, the warehouse would look like this:

####################
##[].......[].[][]##
##[]...........[].##
##[]........[][][]##
##[]......[]....[]##
##..##......[]....##
##..[]............##
##..@......[].[][]##
##......[][]..[]..##
####################
The sum of these boxes' GPS coordinates is 9021.

Predict the motion of the robot and boxes in this new, scaled-up warehouse. What is the sum of all boxes' final GPS coordinates?
const fs = require('fs');
const {log} = require('console');

const [rawmap, rawinstructions] = fs.readFileSync('input.txt', 'utf-8')
    .split('\n\n')
const instructions = rawinstructions.split('\n').flat().join().split('');

function part1(){

    const maplines = rawmap.split('\n');
    const rows = maplines.length
    const cols = maplines[0].length;

    const isWall = (r, c) => maplines[r][c] === '#';
    const isRobot = (r, c) => maplines[r][c] === '@';
    const isBox = (r, c) => maplines[r][c] === 'O';
    const isOpen = (r, c) => maplines[r][c] === '.';
    const replaceAt = (r, c, x) => {
        maplines[r] = maplines[r].substring(0, c) + x + maplines[r].substring(c + 1);
    }

    let robot;
    for (let r = 0; r < maplines.length; r++) {
        for (let c = 0; c < maplines[r].length; c++) {
            if (isRobot(r, c)) {
                robot = [r, c];
                break;
            }
        }
    }
    console.log(maplines, robot);

    for (let instruction of instructions) {
        let cr = robot[0];
        let cc = robot[1];
        let boxesToMove = 0;
        if (instruction === '^') {
            for (let r = robot[0] - 1; r >= 0; r--) {
                if (isWall(r, cc)) {
                    break;
                } else if (isBox(r, cc)) {
                    boxesToMove++;
                } else if (isOpen(r, cc)) {
                    if (boxesToMove > 0) {
                        replaceAt(r, cc, 'O');
                    }
                    replaceAt(cr, cc, '.');
                    replaceAt(cr - 1, cc, '@');
                    robot = [cr - 1, cc];
                    break;
                }
            }
        } else if (instruction === 'v') {
            for (let r = robot[0] + 1; r <= rows; r++) {
                if (isWall(r, cc)) {
                    break;
                } else if (isBox(r, cc)) {
                    boxesToMove++;
                } else if (isOpen(r, cc)) {
                    if (boxesToMove > 0) {
                        replaceAt(r, cc, 'O');
                    }
                    replaceAt(cr, cc, '.');
                    replaceAt(cr + 1, cc, '@');
                    robot = [cr + 1, cc];
                    break;
                }
            }
        } else if (instruction === '<') {
            for (let c = robot[1] - 1; c >= 0; c--) {
                if (isWall(cr, c)) {
                    break;
                } else if (isBox(cr, c)) {
                    boxesToMove++;
                } else if (isOpen(cr, c)) {
                    if (boxesToMove > 0) {
                        replaceAt(cr, c, 'O');
                    }
                    replaceAt(cr, cc, '.');
                    replaceAt(cr, cc - 1, '@');
                    robot = [cr, cc - 1];
                    break;
                }
            }
        } else if (instruction === '>') {
            for (let c = robot[1] + 1; c <= cols; c++) {
                if (isWall(cr, c)) {
                    break;
                } else if (isBox(cr, c)) {
                    boxesToMove++;
                } else if (isOpen(cr, c)) {
                    if (boxesToMove > 0) {
                        replaceAt(cr, c, 'O');
                    }
                    replaceAt(cr, cc, '.');
                    replaceAt(cr, cc + 1, '@');
                    robot = [cr, cc + 1];
                    break;
                }
            }
        }
    }

    let sum = 0;
    for (let r = 0; r < maplines.length; r++) {
        for (let c = 0; c < maplines[r].length; c++) {
            if (isBox(r, c)) {
                sum+= 100 * r + c;
            }
        }
    }
    console.log(sum);
}

function part2() {
    const maplines = rawmap.split('\n');
    let m = [];

    for (let r = 0; r < maplines.length; r++) {
        let ml = '';
        for (let c = 0; c < maplines[r].length; c++) {
            if (maplines[r][c] === 'O') {
                ml += '[]'
            } else if (maplines[r][c] === '.') {
                ml += '..'
            } else if (maplines[r][c] === '#') {
                ml += '##'
            } else if (maplines[r][c] === '@') {
                ml += '@.'
            }
        }
        m.push(ml);
    }

    const rows = m.length
    const cols = m[0].length;

    const isWall = (r, c) => m[r][c] === '#';
    const isRobot = (r, c) => m[r][c] === '@';
    const isBox = (r, c) => isLBox(r, c) || isRBox(r, c);
    const isLBox = (r, c) => m[r][c] === '[';
    const isRBox = (r, c) => m[r][c] === ']';
    const isOpen = (r, c) => m[r][c] === '.';
    const replaceAt = (r, c, x) => {
        m[r] = m[r].substring(0, c) + x + m[r].substring(c + 1);
    }

    const canBoxMoveUp = (r, c) => {
        if (m[r - 1][c] === '#' || m[r - 1][c + 1] === '#') {
            return false;
        }
        if (m[r - 1][c] === '.' && m[r - 1][c + 1] === '.') {
            return true;
        }
        if (m[r - 1][c] === '[') {
            // box right above
            return canBoxMoveUp(r - 1, c);
        }
        if (m[r - 1][c] === ']' && m[r - 1][c + 1] === '[') {
            // 2 boxes
            return canBoxMoveUp(r - 1, c - 1) && canBoxMoveUp(r - 1, c + 1);
        }
        if (m[r - 1][c] === ']') {
            return canBoxMoveUp(r - 1, c - 1);
        }

        if (m[r - 1][c + 1] === '[') {
            return canBoxMoveUp(r - 1, c + 1);
        }
    }

    const moveBoxUp = (r, c) => {
        function move() {
            replaceAt(r - 1, c, '[');
            replaceAt(r - 1, c + 1, ']');
            replaceAt(r, c, '.');
            replaceAt(r, c + 1, '.');
        }

        if (!isBox(r - 1, c) && !isBox(r - 1, c + 1)) {
            move();
        } else {
            if (isLBox(r - 1, c)) {
                moveBoxUp(r - 1, c);
                move();
            } else if (isRBox(r - 1, c) && isLBox(r - 1, c + 1)) {
                moveBoxUp(r - 1, c - 1);
                moveBoxUp(r - 1, c + 1);
                move();
            } else if (isRBox(r - 1, c)) {
                moveBoxUp(r - 1, c - 1);
                move();
            } else if (isLBox(r - 1, c + 1)) {
                moveBoxUp(r - 1, c + 1);
                move();
            }
        }
    }

    const moveBoxDown = (r, c) => {
        function move() {
            replaceAt(r + 1, c, '[');
            replaceAt(r + 1, c + 1, ']');
            replaceAt(r, c, '.');
            replaceAt(r, c + 1, '.');
        }

        if (!isBox(r + 1, c) && !isBox(r + 1, c + 1)) {
            move();
        } else {
            if (isLBox(r + 1, c)) {
                moveBoxDown(r + 1, c);
                move();
            } else if (isRBox(r + 1, c) && isLBox(r + 1, c + 1)) {
                moveBoxDown(r + 1, c - 1);
                moveBoxDown(r + 1, c + 1);
                move();
            } else if (isRBox(r + 1, c)) {
                moveBoxDown(r + 1, c - 1);
                move();
            } else if (isLBox(r + 1, c + 1)) {
                moveBoxDown(r + 1, c + 1);
                move();
            }
        }
    }

    const canBoxMoveDown = (r, c) => {
        if (m[r + 1][c] === '#' || m[r + 1][c + 1] === '#') {
            return false;
        }
        if (m[r + 1][c] === '.' && m[r + 1][c + 1] === '.') {
            return true;
        }
        if (m[r + 1][c] === '[') {
            // box right above
            return canBoxMoveDown(r + 1, c);
        }
        if (m[r + 1][c] === ']' && m[r + 1][c + 1] === '[') {
            // 2 boxes
            return canBoxMoveDown(r + 1, c - 1) && canBoxMoveDown(r + 1, c + 1);
        }
        if (m[r + 1][c] === ']') {
            return canBoxMoveDown(r + 1, c - 1);
        }

        if (m[r + 1][c + 1] === '[') {
            return canBoxMoveDown(r + 1, c + 1);
        }
    }

    let robot;
    for (let r = 0; r < m.length; r++) {
        for (let c = 0; c < m[r].length; c++) {
            if (isRobot(r, c)) {
                robot = [r, c];
                break;
            }
        }
    }

    let index = 0;
    for (let instruction of instructions) {
        // console.log(m);
        // console.log('====', index, '====', instruction);
        index++;
        let cr = robot[0];
        let cc = robot[1];
        let boxesToMove = [];
        if (instruction === '^') {
            const nextR = cr - 1;
            if (isWall(nextR, cc)) continue;
            if (isBox(nextR, cc)) {
                if (isLBox(nextR, cc)) {
                    if (canBoxMoveUp(nextR, cc)) {
                        moveBoxUp(nextR, cc);
                    } else {
                        continue;
                    }
                } else {
                    if (canBoxMoveUp(nextR, cc - 1)) {
                        moveBoxUp(nextR, cc - 1);
                    } else {
                        continue;
                    }
                }
            }
            if (isOpen(nextR, cc) || isBox(nextR, cc)) {
                replaceAt(cr, cc, '.');
                replaceAt(nextR, cc, '@');
                robot = [nextR, cc];
            }
        } else if (instruction === 'v') {
            const nextR = cr + 1;
            if (isWall(nextR, cc)) continue;
            if (isBox(nextR, cc)) {
                if (isLBox(nextR, cc)) {
                    if (canBoxMoveDown(nextR, cc)) {
                        moveBoxDown(nextR, cc);
                    } else {
                        continue;
                    }
                } else {
                    if (canBoxMoveDown(nextR, cc - 1)) {
                        moveBoxDown(nextR, cc - 1);
                    } else {
                        continue;
                    }
                }
            }
            if (isOpen(nextR, cc) || isBox(nextR, cc)) {
                replaceAt(cr, cc, '.');
                replaceAt(nextR, cc, '@');
                robot = [nextR, cc];
            }
        } else if (instruction === '<') {
            for (let c = robot[1] - 1; c >= 0; c--) {
                if (isWall(cr, c)) {
                    break;
                } else if (isLBox(cr, c)) {
                    boxesToMove.push([cr, c]);
                } else if (isOpen(cr, c)) {
                    for (let b of boxesToMove) {
                        replaceAt(b[0], b[1] - 1, '[');
                        replaceAt(b[0], b[1], ']');
                    }
                    replaceAt(cr, cc, '.');
                    replaceAt(cr, cc - 1, '@');
                    robot = [cr, cc - 1];
                    break;
                }
            }
        } else if (instruction === '>') {
            for (let c = robot[1] + 1; c <= cols; c++) {
                if (isWall(cr, c)) {
                    break;
                } else if (isLBox(cr, c)) {
                    boxesToMove.push([cr, c]);
                } else if (isOpen(cr, c)) {
                    for (let b of boxesToMove) {
                        replaceAt(b[0], b[1] + 1, '[');
                        replaceAt(b[0], b[1] + 2, ']');
                    }
                    replaceAt(cr, cc, '.');
                    replaceAt(cr, cc + 1, '@');
                    robot = [cr, cc + 1];
                    break;
                }
            }
        }
    }

    console.log(m);

    let sum = 0;
    for (let r = 0; r < m.length; r++) {
        for (let c = 0; c < m[r].length; c++) {
            if (isLBox(r, c)) {
                sum += 100 * r + c;
            }
        }
    }
    console.log(sum);
}

part2();