from typing import Tuple

import torch


def split_at_placeholder(template: str) -> Tuple[str, str]:
    """
    Splits a string at the position of the "{0}" placeholder.

    Args:
        template: A string containing the "{0}" placeholder exactly once

    Returns:
        Tuple of (before, after) containing the parts before and after the placeholder

    Raises:
        ValueError: If the placeholder is not found in the template
    """
    placeholder = "{0}"
    placeholder_pos = template.find(placeholder)

    if placeholder_pos == -1:
        raise ValueError(f"Placeholder '{placeholder}' not found in template")

    before = template[:placeholder_pos]
    after = template[placeholder_pos + len(placeholder) :]

    return before, after


def clean_process_text_with_placeholder(
    tokenizer,
    template,
    variable_context,
    verbose=False,
    skip_special_tokens=True,
):

    before, after = split_at_placeholder(template)
    start_ids = tokenizer.encode(before, add_special_tokens=not skip_special_tokens)
    middle_ids = tokenizer.encode(variable_context, add_special_tokens=False)
    end_ids = tokenizer.encode(after, add_special_tokens=False)

    start_fixed = [True] * len(start_ids)
    middle_fixed = [False] * len(middle_ids)
    end_fixed = [True] * len(end_ids)

    fixed_positions = start_fixed + middle_fixed + end_fixed

    full_ids = start_ids + middle_ids + end_ids

    if verbose:
        print(f"Full text: {tokenizer.decode(full_ids)}")
    return torch.tensor(full_ids), fixed_positions
