from collections import deque
import random
import sys


def truncate_rdf_list(
    sequence: list[int],
    truncation_probability: float,
    continue_triple_token: int,
    end_of_triple_token: int,
    seed: int = random.randint(0, sys.maxsize),
) -> tuple[list[int], list[int]]:

    if truncation_probability < 0 or truncation_probability > 1:
        raise ValueError("A probability must be between 0 and 1")

    RNG = random.Random(seed)

    END_OF_TRIPLES: deque[int] = deque()

    for i in range(0, len(sequence)):

        TOKEN = sequence[i]
        if TOKEN != end_of_triple_token:
            continue

        END_OF_TRIPLES.append(i + 1)

    TRIPLES_TOKENS: list[int] = []
    TARGET_TRIPLES: list[int] = []

    start_of_triple = 0
    exit_loop = False

    while not exit_loop:

        EOT = END_OF_TRIPLES.popleft()

        TRIPLE = sequence[start_of_triple:EOT]
        TRIPLES_TOKENS.extend(TRIPLE)

        start_of_triple = EOT

        if RNG.random() < truncation_probability:
            exit_loop = True

        if len(END_OF_TRIPLES) == 1:
            exit_loop = True

    TRIPLES_TOKENS.append(
        continue_triple_token
    )

    while len(END_OF_TRIPLES) > 0:

        EOT = END_OF_TRIPLES.popleft()

        TRIPLE = sequence[start_of_triple:EOT]
        TARGET_TRIPLES.extend(TRIPLE)

        start_of_triple = EOT


    return (TRIPLES_TOKENS, TARGET_TRIPLES)

