<?php

// your code goes here

error_reporting(E_ALL);
mb_internal_encoding('utf8');

$text1 = "Кажется, нас обнаружили! Надо срочно уходить отсюда, пока не поздно. Бежим же скорее!";
$text2 = "Ну, прости меня! Не хотела я тебе зла сделать; да в себе не вольна была. Что говорила, что делала, себя не 
помнила.";
$text3 = "Идет гражданская война. Космические корабли повстанцев, наносящие удар с тайной базы, одержали первую победу, 
в схватке со зловещей Галактической Империей.";

function makeFirstCharLowerCase(string $word): string
{
    return mb_strtolower(mb_substr($word, 0, 1)) . mb_substr($word, 1);
}

function makeFirstCharUpperCase(string $word): string
{
    return mb_strtoupper(mb_substr($word, 0, 1)) . mb_substr($word, 1);
}

/**
 * @return array<string>
 * @throws Exception
 */
function makeSentences(string $text): array
{
    $sentences = preg_split('/[.!?]/', $text, -1, PREG_SPLIT_NO_EMPTY);
    if (false === $sentences) {
        throw new Exception(preg_last_error_msg());
    }
    return $sentences;
}

/**
 * @return array<string>
 * @throws Exception
 */
function makeReverseWordsInSentence(string $sentence): array
{
    $words = preg_split('/[-,;:\s]/', $sentence, -1, PREG_SPLIT_NO_EMPTY);
    if (false === $words) {
        throw new Exception(preg_last_error_msg());
    }
    return array_reverse($words);
}

/**
 * @throws Exception
 */
function makeYodaStyleText(string $text): string
{
    $sentences = makeSentences($text);
    $result = '';
    foreach ($sentences as $sentence) {
        $reversedWords = makeReverseWordsInSentence($sentence);
        $reversedWords[0] = makeFirstCharUpperCase($reversedWords[0]);
        $reversedWords[count($reversedWords) - 1] = makeFirstCharLowerCase($reversedWords[count($reversedWords) - 1]);
        $result .= implode(' ', $reversedWords) . '. ';
    }
    return $result;
}

$texts = [$text1, $text2, $text3];
$yodaText = '';

try {
    foreach ($texts as $text) {
        $yodaText = makeYodaStyleText($text);
        echo "Йода говорит: $yodaText\n";
    }
} catch (Exception $e) {
    echo "Произошла ошибка: " . $e->getMessage();
}
