from pathlib import Path
import struct,hashlib,json,sys
F=Path(sys.argv[1] if len(sys.argv)>1 else 'tiff-inputs');F.mkdir(parents=True,exist_ok=True)
def tiff(path,pages):
    tables=[];offset=8
    for p in pages:
        n=11+(p.get('samples',3)==4)
        tables.append((offset,n));offset+=2+n*12+4
    tail=bytearray();dirs=[]
    for i,p in enumerate(pages):
        w,h=p['width'],p['height'];samples=p.get('samples',3);bits=p.get('bits',8)
        tags={256:(4,[w]),257:(4,[h]),258:(3,[bits]*samples),259:(3,[1]),262:(3,[1 if samples==1 else 2]),273:(4,[0]),274:(3,[p.get('orientation',1)]),277:(3,[samples]),278:(4,[h]),279:(4,[len(p['data'])]),284:(3,[1])}
        if samples==4: tags[338]=(3,[2])
        entries=[]
        for tag,(typ,vals) in sorted(tags.items()):
            if tag==273:
                # All per-directory extra values precede its pixel strip.
                extra=sum(len(v)*2 for _,(t,v) in sorted(tags.items()) if t==3 and len(v)*2>4)
                vals=[offset+len(tail)]
            value=struct.pack('<' + ('H' if typ==3 else 'I')*len(vals),*vals)
            if len(value)>4:
                payload=struct.pack('<I',offset+len(tail));tail+=value
            else: payload=value.ljust(4,b'\0')
            entries.append(struct.pack('<HHI',tag,typ,len(vals))+payload)
        tail+=p['data']
        dirs.append(struct.pack('<H',len(entries))+b''.join(entries)+struct.pack('<I',tables[i+1][0] if i+1<len(tables) else 0))
    path.write_bytes(b'II*\0'+struct.pack('<I',8)+b''.join(dirs)+tail)

def rgb(w,h,page=1):
    return bytes(c for y in range(h) for x in range(w) for c in ((18,157,153) if x<w//2 and y<h//2 else (249,179,126) if x>=w//2 and y<h//2 else (55,78,122) if x<w//2 else (244,238,212)))

base={'width':96,'height':64,'data':rgb(96,64)}
for o in [1,6,8]: tiff(F/f'orientation-{o}.tiff',[{**base,'orientation':o}])
tiff(F/'three-pages.tiff',[base,{'width':73,'height':41,'data':rgb(73,41)}, {'width':48,'height':80,'data':rgb(48,80)}])
gray=bytes(b for y in range(32) for x in range(256) for b in struct.pack('<H',12000+x if y<16 else x*257))
tiff(F/'gray16.tiff',[{'width':256,'height':32,'samples':1,'bits':16,'data':gray}])
alpha=bytes(c for y in range(48) for x in range(128) for c in (18,157,153,[0,64,128,255][x//32]))
tiff(F/'alpha-bands.tiff',[{'width':128,'height':48,'samples':4,'data':alpha}])
white=bytes(c for y in range(48) for x in range(128) for c in ((18,157,153) if 24<x<104 and 10<y<38 else (255,255,255)))
tiff(F/'painted-white.tiff',[{'width':128,'height':48,'data':white}])
tiff(F/'twenty-one-pages.tiff',[{'width':8,'height':8,'data':rgb(8,8)}]*21)
(F/'truncated-strip.tiff').write_bytes((F/'orientation-1.tiff').read_bytes()[:-1000])
(F/'no-pages.tiff').write_bytes(b'II*\0\0\0\0\0')
(F/'bigtiff.tiff').write_bytes(b'II+\0\x08\0\0\0'+b'\0'*16)
(F/'not-tiff.tiff').write_bytes(b'This is plain text, not an image.')

print(json.dumps([{'name':p.name,'bytes':p.stat().st_size,'sha256':hashlib.sha256(p.read_bytes()).hexdigest()} for p in sorted(F.glob('*.tiff'))],indent=2))
