from typing import List
from typing import Tuple


def insert_pattern(
    tokens: List[str], target_idx: int, pattern: str
) -> Tuple[List[str], int]:
    """
    Pattern must contain '{predict}' token.
    Token '{target}' and token '{predict}' are replaced
        by the target word.

    Args:
        tokens: context represented as a list of tokens
        target_idx: replacement position
        pattern: string that represents a pattern, e.g. For example '{target} and {predict}'

    Returns:
        modified context and modified target position
    """
    if not pattern:
        return tokens, target_idx

    target = tokens[target_idx]

    try:
        lctx, rctx = [
            s.format(target=target).strip().split(" ")
            for s in pattern.split("{predict}")
        ]
    except ValueError:
        raise ValueError('pattern must have exactly one token "{predict}"')

    lctx, rctx = [
        [token for token in ctx if token] for ctx in [lctx, rctx]
    ]  # drop empty strings: ''

    mod_target = target_idx + len(lctx)
    mod_tokens = tokens[:target_idx] + lctx + [target] + rctx + tokens[target_idx + 1 :]

    return mod_tokens, mod_target