from typing import Tuple
import re


def adjust_USFM_line(raw_fields:Tuple[int,int,int,str]) -> Tuple[int,int,int,str,str,str]:
    """
    Takes the raw USFM line, then
        1/ Splits the line into marker (including leading backslash) and rest
        2/ Removes existing x-tw="..." links
        3/ Removes k-s/k-e milestones (possibly leaving blank lines)
    """
    # print(f"      adjust_USFM_line({raw_fields})…")
    line_number, C, V, line = raw_fields

    # Handle special case
    if line == '\\k-e\\*': # only
        # we want to delete the entire line (rather than leaving in a superfluous blank line)
        return line_number, C, V, 'SKIP', 'SKIP', 'SKIP'

    # Remove existing TW links from USFM line
    if 'x-tw' in line:
        line = re.sub(' ?x-tw=".+?"', '', line)
        if 'x-tw' in line: # likely a missing closing quote or something
            raise Exception(f"Seems bad USFM line -- please fix first -- in line {line_number}, {C}:{V}, '{raw_fields[3]}'")

    # Remove \k start and end milestones from line
    line = line.replace('\\k-s |\\*', '')
    line = line.replace('\\k-e\\*', '')
    assert '\\k' not in line, f"\\k shouldn't be in line: '{line}'"

    # Separate into marker and rest
    # NOTE: Some lines start with opening punctuation, e.g., "(\w ...") -- this all goes in rest
    if line.startswith('\\'):
        if ' ' in line: marker, rest = line.split(' ', 1)
        else: marker, rest = line, ''
    else: marker, rest = '', line
    # print(f"        adjust_USFM_line returning {source_filepath}, {line_number}, {C}, {V} '{marker}', '{rest}'")

    return line_number, C, V, line, marker, rest