from pathlib import Path
import json
from PIL import Image, ImageOps, ImageDraw
from reportlab.pdfgen import canvas
from pypdf import PdfReader, PdfWriter

items=json.loads(Path('tmp/pdfs/manifest.json').read_text())
titles={'survey':'Community Survey','enrolment':'Service User Enrolment','screening':'Hearing and Vision Screening','iep':'Individualised Education Plan','pfp':'Personal Future Plan','passport':'Personal Passport','network-registration':'Network Registrations'}
combined=PdfWriter()
for name,title in titles.items():
    selected=[x for x in items if x['name']==name]
    target=Path('output/pdf')/(name+'-mockups.pdf')
    c=canvas.Canvas(str(target));c.setTitle(title+' - Web and Mobile Mockups');c.setAuthor('Sense India project mockups')
    for i,item in enumerate(selected):
        with Image.open(item['file']) as im: w,h=im.size
        width=840 if item['view']=='web' else 420
        margin=24; imagewidth=width-2*margin; imageheight=h*imagewidth/w; height=imageheight+92
        c.setPageSize((width,height));c.setFillColorRGB(.278,.133,.31)
        c.setFont('Helvetica-Bold',14);c.drawString(margin,height-25,title)
        c.setFont('Helvetica',9);c.drawString(margin,height-42,item['view'].title()+' | '+item['title'].replace('·','-'))
        c.drawImage(item['file'],margin,30,width=imagewidth,height=imageheight)
        c.setFont('Helvetica',8);c.drawString(margin,14,'Design prototype | Static snapshot | '+str(i+1)+' / '+str(len(selected)))
        c.showPage()
    c.save()
    reader=PdfReader(target);assert len(reader.pages)==len(selected)
    combined.append(str(target),outline_item=title)
    print(target,len(reader.pages),'pages')
combined.write('output/pdf/all-mockups.pdf')
# A contact sheet for visual inspection across all exports.
thumbs=[]
for item in items:
    with Image.open(item['file']) as im:
        im=im.convert('RGB'); im.thumbnail((240,340))
        tile=Image.new('RGB',(260,380),'#e9e5ec');tile.paste(im,((260-im.width)//2,24))
        ImageDraw.Draw(tile).text((8,5),item['name']+' '+item['view']+' '+item['title'][:20],fill='#47224f')
        thumbs.append(tile)
for start in range(0,len(thumbs),20):
    group=thumbs[start:start+20];sheet=Image.new('RGB',(1300,380*((len(group)+4)//5)),'white')
    for j,tile in enumerate(group):sheet.paste(tile,((j%5)*260,(j//5)*380))
    sheet.save('tmp/pdfs/contact-'+str(start//20)+'.jpg')
