import re

_PATTERN = re.compile(
    r'^\s*'
    r'(?:(?P<h>\d+)\s*h\s*)?'
    r'(?:(?P<m>\d+)\s*m\s*)?'
    r'(?:(?P<s>\d+)\s*s)?'
    r'\s*$'
)


def parse_duration(text):
    if not isinstance(text, str):
        raise ValueError('invalid duration')
    match = _PATTERN.match(text)
    if not match or (not match.group('h') and not match.group('m') and not match.group('s')):
        raise ValueError('invalid duration')
    seconds = 0
    if match.group('h') is not None:
        seconds += int(match.group('h')) * 3600
    if match.group('m') is not None:
        seconds += int(match.group('m')) * 60
    if match.group('s') is not None:
        seconds += int(match.group('s'))
    return seconds
