from typing import OrderedDict


def extract_line_level_data(data):
    """
    data (dict): as derived from standard Watson API JSON

    returns: a list of dictionary, each sub-list representing a line:
    {
       "start": 1.42,
       "end": 3.8,
       "confidence": 0.999,
       "words": [
            {
                "text": "Hello",
                "start": 1.42,
                "end": 2.4,
                "confidence": 0.93
            }
       ]
    }
    """
    lines = []
    for result in data['results']:
        if result.get('alternatives'):
            # just pick best alternative
            alt = result.get('alternatives')[0]
            timestamps = alt['timestamps']
            if timestamps: # for some reason, timestamps can be empty in some cases
                words = []
                word_confidences = alt['word_confidence']
                for idx, tobject in enumerate(alt['timestamps']):
                    txt, tstart, tend = tobject
                    word = OrderedDict()
                    word["start"] = tstart
                    word["end"] = tend
                    word['confidence'] = word_confidences[idx][1]
                    word["text"] = txt
                    words.append(word)
                line = OrderedDict()
                line['start'] = words[0]['start']
                line['end'] = words[-1]['end']
                line['confidence'] = alt['confidence']
                line['word_count'] = len(words)
                line['words'] = words
                lines.append(line)

    return lines