from typing import List
from typing import Tuple
import re


def get_subphrases(line: str) -> List[Tuple[str, str]]:
    """
	Given a ground truth transcription, extracts all subphrases.
	A subphrase is defined as a set of words with a single timestamp.
	In our ground truth file, it is possible for a single line to contain multiple timestamps,
	corresponding to different phrases. This function extracts each individual phrase
	so we can create the json file with precise timestamps.

	:param line: Text from the transcription file.
	:return: List of subphrases, where each subphrase is defined by the timestamp and words.
	"""
    # Find all timestamps on this line.
    # Finds: `[TIME: MM:SS]:` with or without the leading or ending colon.
    patterns = [
        (r"\[+TIME: \d+:[0-5][0-9]\]", len("[TIME: MM:SS]")),
        (r"\[+TIME: \d+:[0-5][0-9]\]: ", len("[TIME: MM:SS]:")),
        (r"\[+TIME \d+:[0-5][0-9]\]", len("[TIME MM:SS]:")),
        (r"\[+TIME \d+:[0-5][0-9]\]:", len("[TIME MM:SS]:")),
    ]

    meta = []
    for item in patterns:
        p, _ = item
        idxs = [m.span() for m in re.finditer(p, line)]
        meta += idxs
    meta = list(reversed(meta))

    # Only one phrase in this line.
    subphrases = []
    if len(meta) == 1:
        start, end = meta[0]
        ts, text = line[start:end], line[end:]
        item = (ts, text)
        subphrases.append(item)
    elif len(meta) > 1:
        # Extract the text for the subphrase.
        for i in range(len(meta)):
            start, end = meta[i]
            ts = line[start:end]
            text_start = end
            # If this is the last phrase.
            if i == len(meta) - 1:
                text = line[text_start:]
            else:
                next_idx, _ = meta[i + 1]
                text = line[text_start:next_idx]

            item = (ts, text)
            subphrases.append(item)

    return subphrases