import logging
import struct


def read_lc3_file(filepath):
    filepath = filepath.replace('file:', '')
    with open(filepath, 'rb') as f_lc3:
        header = struct.unpack('=HHHHHHHI', f_lc3.read(18))
        if header[0] != 0xcc1c:
            raise ValueError('Invalid bitstream file')

        # found in liblc3 - decoder.py
        samplerate = header[2] * 100
        nchannels = header[4]
        frame_duration = header[5] * 10
        stream_length = header[7]
        #lc3_frame_size = struct.unpack('=H', f_lc3.read(2))[0]
        logging.info('Loaded lc3 file: %s', filepath)
        logging.info('samplerate: %s', samplerate)
        logging.info('nchannels %s', nchannels)
        logging.info('frame_duration %s', frame_duration)
        logging.info('stream_length %s', stream_length)

        chunks = []
        while True:
            b = f_lc3.read(2)
            if b == b'':
                break
            lc3_frame_size = struct.unpack('=H', b)[0]
            chunks.append(f_lc3.read(lc3_frame_size))

        return b''.join(chunks)