<?php

$cards = range(0, 10006);

$commands = explode("\n", file_get_contents('input.txt'));

function deal_into_new_stack(array $cards)
{
    return array_reverse($cards);
}

function cut(array $cards, $n_card)
{
    $slice = array_splice($cards, 0, $n_card);
    return array_merge($cards, $slice);
}

function deal_with_increment(array $cards, $n)
{
    $new_cards = [];
    $deck_length = count($cards);
    $card_index = 0;
    $i = 0;
    while($deck_length !== count($new_cards)) {
        for (; $i < $deck_length; $i += $n) {
            $new_cards[$i] = $cards[$card_index];
            $card_index++;
        }
        $i = abs($deck_length - $i);
    }

    ksort($new_cards);
    return $new_cards;
}

foreach ($commands as $command) {
    if (strpos($command, 'deal with increment') === 0) {
        $cards = deal_with_increment($cards, (int) substr($command, 20));
    }
    if (strpos($command, 'cut') === 0) {
        $cards = cut($cards, (int) substr($command, 4));
    }
    if ('deal into new stack' === $command) {
        $cards = deal_into_new_stack($cards);
    }
}

echo array_search(2019, $cards, true);