from typing import Counter
import re


def is_valid_sentence(str):
    """
    Check if a sentence is valid:
    - Does not contain mismatched brackets
    - Does not start with 'and' or 'but'
    - Ends with a punctuation [.?!]
    - Has a minimum length of 5
    """

    start_pattern = r"^\"*[A-Z]+"
    end_pattern = r"(\.\?\!)\"*$"

    tokens = str.strip().split('\t')

    if len(tokens) != 2:
        return False, None, None

    sid, sent = tokens 
    normalized = sent.replace('``', '\"')
    normalized = normalized.replace('\'\'', '\"')

    # filtering
    # unmatched brackets
    count = Counter(normalized)
    if count['\"'] % 2 != 0:
        valid = False
    # sentences start with 'and' and 'but'
    elif normalized.lower().startswith('and') or normalized.lower().startswith('but'):
        valid = False
    # check start and end of word
    elif not re.search(start_pattern, normalized) and not re.search(end_pattern, normalized): 
        valid = False
    elif len(normalized.split()) < 5:
        valid = False
    else:
        valid = True

    return valid, sid, sent