import random
import logging

logging.basicConfig(level=logging.ERROR)


def generate_arithmetic_sequence(start: int, difference: int, length: int) -> list[int]:
    """Generates an arithmetic sequence.

    Args:
        start: The starting value of the sequence.
        difference: The common difference between consecutive terms.
        length: The number of terms in the sequence.

    Returns:
        A list of integers representing the arithmetic sequence.
    """
    try:
        sequence = [start + i * difference for i in range(length)]
        return sequence
    except Exception as e:
        logging.error(f"Error generating arithmetic sequence: {e}")
        return []


def predict_next_element(sequence: list[int]) -> int | None:
    """Prompts the user to predict the next element in a sequence.

    Args:
        sequence: A list of integers representing the sequence.

    Returns:
        The user's prediction as an integer, or None if the input is invalid.
    """
    try:
        print(f"The sequence is: {sequence}")
        user_input = input("Predict the next element: ")
        prediction = int(user_input)
        return prediction
    except ValueError:
        print("Invalid input. Please enter an integer.")
        return None
    except Exception as e:
        logging.error(f"Error getting user prediction: {e}")
        return None


def evaluate_prediction(sequence: list[int], prediction: int) -> bool:
    """Evaluates the user's prediction against the actual next element.

    Args:
        sequence: The list of integers representing the sequence.
        prediction: The user's prediction.

    Returns:
        True if the prediction is correct, False otherwise.
    """
    try:
        actual_next_element = sequence[-1] + (sequence[1] - sequence[0])
        return prediction == actual_next_element
    except (IndexError, TypeError) as e:
        logging.error(f"Error evaluating prediction: {e}")
        return False


def main():
    """Main function to run the intuition trainer."""
    start = random.randint(1, 10)
    difference = random.randint(1, 5)
    length = random.randint(3, 6)
    sequence = generate_arithmetic_sequence(start, difference, length)

    if not sequence:
        print("Failed to generate a sequence.")
        return

    prediction = predict_next_element(sequence)

    if prediction is None:
        return

    if evaluate_prediction(sequence, prediction):
        print("Correct! You have a good intuition for this pattern.")
    else:
        print(
            f"Incorrect. The next element should have been {sequence[-1] + (sequence[1] - sequence[0])}."
        )


if __name__ == "__main__":
    main()