from typing import Dict
from typing import List


def _chunkify(ctx: Dict, doc_id: str, cid_start: int, max_len: int) -> List[Dict]:
    """
    Break context into chunks of size max_len
    :param ctx: context dict
    :param doc_id: document id
    :param cid_start: start of CID incrementation
    :param max_len: max sentences per context
    :return:
    """
    # break sentences into chunks
    sent_chunks = [
        ctx['sentences'][i:i + max_len]
        for i in range(0, len(ctx['sentences']), max_len)
    ]

    # create ctx entry for each chunk of sentences
    ctx_chunks = []
    for ctx_offset, sent_chunk in enumerate(sent_chunks):
        cid = cid_start + ctx_offset
        text_start = sent_chunk[0]['start']
        text_end = sent_chunk[-1]['end'] + 1
        if ctx['text'][text_start:text_end].strip():
            new_ctx = {
                'section': ctx['section'],
                'context_id': f"{doc_id}-C{cid:03d}",
                'text': ctx['text'][text_start:text_end],
                'sentences': [{
                    'sentence_id': f"{doc_id}-C{cid:03d}-S{sid:03d}",
                    'start': sent['start'] - text_start,
                    'end': sent['end'] - text_start
                } for sid, sent in enumerate(sent_chunk)]
            }
            ctx_chunks.append(new_ctx)

    return ctx_chunks