"""Original CC0 RTF sources; expected body controls precede converter execution."""
from pathlib import Path
import hashlib, json, struct, zlib

root = Path.cwd()
folder = root / 'benchmarks/fixtures/rtf-content1'
folder.mkdir(exist_ok=False)
def u(text):
    out = ''
    for ch in text:
        if ch in '\\{}': out += '\\' + ch
        elif 32 <= ord(ch) < 127: out += ch
        else:
            raw = ch.encode('utf-16-le')
            for n in range(0, len(raw), 2):
                code = int.from_bytes(raw[n:n+2], 'little')
                out += '\\u' + str(code if code < 32768 else code - 65536) + '?'
    return out
head = r'{\rtf1\ansi\ansicpg1252\uc1\deff0{\fonttbl{\f0\fswiss Liberation Sans;}}\paperw12240\paperh15840\margl1440\margr1440\margt1440\margb1440\f0\fs24'
paragraphs = ['A_START plain A_END', 'U_START Ω Ж 世界 😀 café U_END', 'L_START first\nsecond\tTAB L_END', '', 'X_START <tag> &copy; **literal** [square] X_END', 'ALT_START 世界 ALT_END', 'Z_START final Z_END']
body = [u(p).replace('\\u10?', r'\line ').replace('\\u9?', r'\tab ') for p in paragraphs]
body[1] = body[1].replace('caf\\u233?', r"caf\'e9")
body[5] = r'ALT_START {\upr{ANSI_MUST_NOT_APPEAR}{\*\ud ' + u('世界') + r'}} ALT_END'
plain = head + r'{\header HEADER_NOT_BODY}{\footer FOOTER_NOT_BODY}\pard ' + r'\par '.join(body) + r'\par}'
(folder/'breaks.rtf').write_bytes(plain.encode('ascii'))
def chunk(name, data):
    return struct.pack('>I', len(data)) + name + data + struct.pack('>I', zlib.crc32(name+data))
w,h = 48,32
rgba = bytes(c for y in range(h) for x in range(w) for c in ((x*5)%256,(y*7)%256,((x+y)*3)%256,255))
rows = b''.join(b'\0'+rgba[y*w*4:(y+1)*w*4] for y in range(h))
png = b'\x89PNG\r\n\x1a\n'+chunk(b'IHDR',struct.pack('>IIBBBBB',w,h,8,6,0,0,0))+chunk(b'IDAT',zlib.compress(rows))+chunk(b'IEND',b'')
(folder/'pattern.png').write_bytes(png)
rich = head + r'{\stylesheet{\s0 Normal;}{\s1\sbasedon0\outlinelevel0 Heading 1;}}{\header RICH_HEADER_NOT_BODY}{\footer RICH_FOOTER_NOT_BODY}'
rich += r'\pard\s1 CONTENT_HEADING\par\pard\s0 RICH_START '+u('Ω Ж café')+r'\par '
rich += r'BOLD_START {\b bold text} {\i italic text} {\ul underlined text} BOLD_END\par '
rich += r'LINK_START {\field{\*\fldinst HYPERLINK "https://example.invalid/rtf-content?x=1&y=2"}{\fldrslt Useful link}} LINK_END\par '
rich += r'\trowd\cellx2800\cellx6000\intbl CELL_A\cell CELL_B\cell\row '
rich += r'\trowd\cellx2800\cellx6000\intbl CELL_C\cell CELL_D\cell\row\pard '
rich += r'IMAGE_START {\pict\pngblip\picw48\pich32\picwgoal720\pichgoal480 '+png.hex()+r'} IMAGE_END\par '
rich += r'NOTE_START note reference{\super\chftn}{\footnote\pard\plain\f0\fs20 {\super\chftn} FOOTNOTE_BODY} NOTE_END\par '
rich += r'FINAL_MARKER\par}'
(folder/'rich.rtf').write_bytes(rich.encode('ascii'))
manifest = {'license':'CC0-1.0; original fixtures authored for Tabmorph; no user content', 'settings':'Original ASCII RTF1 with explicit CP1252 / UTF16 Unicode controls; no timestamps, transcripts or editing data', 'cases':[
 {'id':'breaks','source':'benchmarks/fixtures/rtf-content1/breaks.rtf','bodyParagraphs':paragraphs,'expectedTxt':''.join(p+'\n\n'for p in paragraphs),'omitted':['HEADER_NOT_BODY','FOOTER_NOT_BODY','ANSI_MUST_NOT_APPEAR']},
 {'id':'rich','source':'benchmarks/fixtures/rtf-content1/rich.rtf','requiredInOrder':['CONTENT_HEADING','RICH_START','BOLD_START','BOLD_END','LINK_START','Useful link','LINK_END','CELL_A','CELL_B','CELL_C','CELL_D','IMAGE_START','IMAGE_END','NOTE_START','NOTE_END','FINAL_MARKER'],'cells':[['CELL_A','CELL_B'],['CELL_C','CELL_D']],'link':'https://example.invalid/rtf-content?x=1&y=2','image':{'width':w,'height':h,'rgbaSha256':hashlib.sha256(rgba).hexdigest()},'omitted':['RICH_HEADER_NOT_BODY','RICH_FOOTER_NOT_BODY']}
]}
manifest['files'] = {p.name:{'bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()}for p in sorted(folder.iterdir())}
(folder/'manifest.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2)+'\n')
print(json.dumps({'corpora':2,'files':manifest['files']}))
