"""Owned plain-text UTF-8 partition at whitespace boundaries; no synthesis or vendor request."""
import hashlib,json,re
def partition(text,budget,input_type='plain'):
    if input_type!='plain':raise ValueError('SSML is outside this partition contract')
    if type(budget)is not int or budget<1:raise ValueError('positive integer byte budget')
    text.encode('utf-8','strict')
    if not text:return {'text_sha256':hashlib.sha256(b'').hexdigest(),'byte_budget':budget,'chunks':[]}
    tokens=re.findall(r'\s+|\S+',text);assert ''.join(tokens)==text;units=[]
    for token in tokens:
        if len(token.encode('utf-8'))<=budget:units.append(token)
        elif token.isspace():
            piece=''
            for c in token:
                if len(c.encode('utf-8'))>budget:raise ValueError('single whitespace codepoint exceeds budget')
                if len((piece+c).encode('utf-8'))>budget:units.append(piece);piece=''
                piece+=c
            if piece:units.append(piece)
        else:raise ValueError('unbreakable non-whitespace token exceeds budget; revise text or contract')
    groups=[];piece=''
    for unit in units:
        if piece and len((piece+unit).encode('utf-8'))>budget:groups.append(piece);piece=''
        piece+=unit
    if piece:groups.append(piece)
    rows=[];cp=0;byte=0
    for i,chunk in enumerate(groups):
        b=chunk.encode('utf-8');assert 0<len(b)<=budget
        rows.append({'sequence_zero_based':i,'text':chunk,'start_codepoint':cp,'end_codepoint_exclusive':cp+len(chunk),'start_utf8_byte':byte,'end_utf8_byte_exclusive':byte+len(b),'utf8_bytes':len(b),'sha256':hashlib.sha256(b).hexdigest()});cp+=len(chunk);byte+=len(b)
    assert ''.join(x['text']for x in rows)==text and cp==len(text)and byte==len(text.encode('utf-8'))
    assert all(text[x['start_codepoint']:x['end_codepoint_exclusive']]==x['text']for x in rows)
    return {'text_sha256':hashlib.sha256(text.encode('utf-8')).hexdigest(),'byte_budget':budget,'policy':'greedy complete non-whitespace tokens; whitespace preserved and may split at codepoint boundaries; no linguistic sentence or general grapheme segmentation','chunks':rows}
def demo():
    text='  سلام 🙂  می‌رویم.\nسطر بعد ا\u0654 است.  ';r=partition(text,24)
    assert len(r['chunks'])>1 and any('می‌رویم.'in x['text']for x in r['chunks'])and any('ا\u0654'in x['text']for x in r['chunks'])
    assert partition('',24)['chunks']==[]
    spaces=partition(' '*50,7);assert ''.join(x['text']for x in spaces['chunks'])==' '*50
    invalid=[]
    for t,b,kind in [('خیلیبلند',3,'plain'),('a',True,'plain'),('<speak>a</speak>',24,'ssml'),('\ud800',24,'plain')]:
        try:partition(t,b,kind)
        except(ValueError,UnicodeEncodeError):invalid.append(True)
        else:raise AssertionError('invalid input accepted')
    return {'authored_text':text,'actual_partition':r,'empty_text_supported':True,'fifty_whitespace_preserved_with_budget7':spaces,'four_explicit_invalid_cases_rejected':invalid,'budget24_is_authored_not_service_quota':True,'vendor_request_audio_synthesis_or_joined_prosody_tested':False}
if __name__=='__main__':print(json.dumps(demo(),ensure_ascii=False,indent=2))
