"""Make the original Portable Laptop Guide file-handoff samples.
Example: python reproduce.py ./samples
Requires Python 3, Pillow, ReportLab, PyMuPDF >= 1.24.2, DejaVu Sans,
FFmpeg/ffprobe with libx264, Poppler pdftotext and fontconfig (or --font).
"""
import argparse
import json
import subprocess
from pathlib import Path

import fitz
import PIL
import reportlab
from PIL import Image, ImageDraw, ImageFont
from reportlab.lib.colors import HexColor
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
from reportlab.pdfgen import canvas

parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('directory', type=Path)
parser.add_argument('--font', type=Path)
options = parser.parse_args()
out = options.directory.resolve()
out.mkdir(exist_ok=True, parents=True)

def call(args):
    return subprocess.check_output(list(map(str, args)), stderr=subprocess.PIPE)

font_file = options.font or Path(call(['fc-match','-f','%{file}','DejaVu Sans']).decode())
pdfmetrics.registerFont(TTFont('NotesSans', str(font_file)))
width, height = 420, 340
ink, accent, muted = '#152c3b', '#136a68', '#4b626d'

def document(name, title, caption):
    page = canvas.Canvas(str(out/name), pagesize=(width,height), invariant=1)
    page.setTitle(title)
    page.setAuthor('Portable Laptop Guide')
    def line(x,y,text,size=12,color=ink):
        page.setFillColor(HexColor(color))
        page.setFont('NotesSans', size)
        page.drawString(x,y,text)
    line(26,307,'PORTABLE LAPTOP GUIDE  /  FILE STUDIES',9,accent)
    line(26,265,title,22)
    line(26,241,caption,10,muted)
    page.setStrokeColor(HexColor('#b5c7c9'))
    page.line(26,222,394,222)
    return page,line

def extract(name):
    return call(['pdftotext','-layout','-enc','UTF-8',out/name,'-']).decode()

def proof():
    names = ['Şişli', 'Iğdır', 'İzmir', 'Çanakkale']
    (out/'proof-words.txt').write_text('\n'.join(names)+'\n',encoding='utf-8')
    page,line = document('proof-text.pdf','Destination proof','Reference list for a Turkish-to-English quotation.')
    for num,name in enumerate(names,1):
        y=190-(num-1)*34
        line(27,y,f'0{num}',11,muted)
        line(65,y,name,18)
    line(26,37,'Check the spelling before and after copying from the PDF.',10,muted)
    page.save()
    with fitz.open(out/'proof-text.pdf') as doc, fitz.open() as raster:
        source = doc[0].get_pixmap(matrix=fitz.Matrix(2,2),alpha=False)
        sheet = raster.new_page(width=width,height=height)
        sheet.insert_image(sheet.rect,stream=source.tobytes('png'))
        raster.save(out/'proof-image.pdf',garbage=4,deflate=True)
    results = {}
    for name in ('proof-text.pdf','proof-image.pdf'):
        text = extract(name)
        results[name] = {'extracted_names':[n for n in names if n in text],
                         'extracted_nonwhitespace_characters':sum(not c.isspace() for c in text)}
    assert len(results['proof-text.pdf']['extracted_names']) == 4
    assert results['proof-image.pdf']['extracted_nonwhitespace_characters'] == 0
    return results

def drawings():
    page,line = document('drawing-base.pdf','Alcove observation','Practice elevation / room 2B / sample dimensions in mm')
    page.setStrokeColor(HexColor('#607783'))
    page.setLineWidth(2)
    frame = [(64,96),(64,190),(313,190),(313,96),(297,96),(297,172),(80,172),(80,96)]
    line_path = page.beginPath()
    line_path.moveTo(*frame[0])
    for x,y in frame[1:]:
        line_path.lineTo(x,y)
    page.drawPath(line_path)
    line(100,143,'M1  front  1,146 mm',14)
    line(100,111,'M2  rear   1,139 mm',14)
    line(26,37,'Use the comment attached to M2 to find the follow-up action.',10,muted)
    page.save()
    note='M2: remeasure the rear opening at skirting height.'
    with fitz.open(out/'drawing-base.pdf') as doc:
        rect=fitz.Rect(91,height-131,279,height-104)
        annotation=doc[0] # retain page reference for the lifetime of the annotation
        mark=annotation.add_rect_annot(rect)
        mark.set_colors(stroke=(0.75,0.24,0.07))
        mark.set_border(width=2)
        mark.set_info(title='PLG file study',content=note)
        mark.update()
        doc.save(out/'drawing-comment.pdf',garbage=4,deflate=True)
    with fitz.open(out/'drawing-comment.pdf') as doc:
        doc.bake(annots=True, widgets=False)
        doc.save(out/'drawing-flat.pdf',garbage=4,deflate=True)
    result={}
    pixels=[]
    for name in ('drawing-comment.pdf','drawing-flat.pdf'):
        with fitz.open(out/name) as doc:
            sheet=doc[0]
            notes=[m.info['content'] for m in sheet.annots()]
            result[name]={'annotation_count':len(notes),'comment_bodies':notes,
                          'M2_in_page_text':'M2' in sheet.get_text()}
            pix=sheet.get_pixmap(matrix=fitz.Matrix(2,2),alpha=False,annots=True)
            pixels.append(pix.samples)
    result['different_rendered_rgb_bytes_at_144dpi']=sum(a!=b for a,b in zip(*pixels))
    assert result['drawing-comment.pdf']['comment_bodies'] == [note]
    assert result['drawing-flat.pdf']['annotation_count'] == 0
    assert len(pixels[0]) == len(pixels[1])
    assert result['different_rendered_rgb_bytes_at_144dpi'] == 0
    assert all(result[n]['M2_in_page_text'] for n in ('drawing-comment.pdf','drawing-flat.pdf'))
    return result

def ff(args):
    return ['ffmpeg','-hide_banner','-loglevel','error','-y',*map(str,args)]

colors=[(22,139,125),(203,101,39),(95,99,190)]
cuts=[0,48,84]
names=['Establish the room','Check the detail','Confirm the change']

def clips():
    dims=(960,540)
    rate=24
    fonts={s:ImageFont.truetype(str(font_file),s) for s in [20,22,29,47,62]}
    cmd=ff(['-f','rawvideo','-pix_fmt','rgb24','-s','960x540','-r','24','-i','pipe:0',
            '-an','-c:v','libx264','-threads','1','-preset','medium','-crf','18',
            '-pix_fmt','yuv420p','-movflags','+faststart',out/'edit-source.mp4'])
    encoder=subprocess.Popen(cmd,stdin=subprocess.PIPE)
    for frame in range(120):
        shot=max(i for i,cut in enumerate(cuts) if frame>=cut)
        img=Image.new('RGB',dims,(19,37,49))
        pen=ImageDraw.Draw(img)
        pen.text((50,37),'PORTABLE LAPTOP GUIDE   /   EDITING SAMPLE',font=fonts[20],fill=(162,201,195))
        pen.rectangle((52,129,238,306),fill=colors[shot])
        pen.text((109,174),chr(65+shot),font=fonts[62],fill='white')
        pen.text((274,135),f'SHOT {shot+1} OF 3',font=fonts[22],fill=(162,201,195))
        pen.text((271,183),names[shot],font=fonts[47],fill='white')
        pen.text((53,367),f'Frame {frame:03d} / 119',font=fonts[29],fill='white')
        pen.text((679,372),'24 fps  /  silent',font=fonts[22],fill=(162,201,195))
        pen.rectangle((54,447,904,457),fill=(69,88,100))
        pen.rectangle((54,447,54+int(850*frame/119),457),fill=(139,205,193))
        for cut in cuts[1:]:
            x=54+int(850*cut/119)
            pen.line((x,434,x,469),fill='white',width=2)
        encoder.stdin.write(img.tobytes())
    encoder.stdin.close()
    if encoder.wait():
        raise RuntimeError('Source encoding failed')
    call(ff(['-i',out/'edit-source.mp4','-vf','scale=480:270:flags=lanczos',
             '-an','-c:v','libx264','-threads','1','-preset','medium','-crf','26',
             '-pix_fmt','yuv420p','-movflags','+faststart',out/'edit-proxy.mp4']))
    result={}
    for name in ('edit-source.mp4','edit-proxy.mp4'):
        file=out/name
        stream=json.loads(call(['ffprobe','-v','error','-select_streams','v:0','-count_frames',
                    '-show_entries','stream=width,height,avg_frame_rate,duration,nb_read_frames',
                    '-of','json',file]))['streams'][0]
        # Read a color block inside the slate, away from the letter or border, in each decoded frame.
        x=int(stream['width']*.08)//2*2
        y=int(stream['height']*.30)//2*2
        raw=call(ff(['-i',file,'-vf',f'crop=4:4:{x}:{y},scale=1:1','-f','rawvideo','-pix_fmt','rgb24','pipe:1']))
        ids=[min(range(3),key=lambda j:sum((c-d)**2 for c,d in zip(raw[i:i+3],colors[j])))
             for i in range(0,len(raw),3)]
        changes=[i for i,shot in enumerate(ids) if i==0 or shot!=ids[i-1]]
        result[name]={'bytes':file.stat().st_size,'stream':stream,'shot_start_frames':changes}
        assert changes==cuts and len(ids)==120 and stream['nb_read_frames']=='120'
    return result

def side_by_side():
    # Decode both delivered files, then place the decoded images side by side.
    # The text below each pair reports the frame under review.
    tile = (432, 244)
    frame_size = tile[0] * tile[1] * 3
    decoded = []
    for name in ('edit-source.mp4','edit-proxy.mp4'):
        decoded.append(call(ff(['-i',out/name,'-vf','scale=432:244','-pix_fmt','rgb24',
                                '-f','rawvideo','pipe:1'])))
    assert all(len(clip) == 120*frame_size for clip in decoded)
    fonts={size:ImageFont.truetype(str(font_file),size) for size in (17,22,28,40)}
    encoder=subprocess.Popen(ff(['-f','rawvideo','-pix_fmt','rgb24','-s','960x486','-r','24',
                         '-i','pipe:0','-an','-c:v','libx264','-threads','1','-crf','21',
                         '-pix_fmt','yuv420p','-movflags','+faststart',out/'cut-comparison.mp4']),
                         stdin=subprocess.PIPE)
    for i in range(120):
        sheet=Image.new('RGB',(960,486),(244,245,237))
        pen=ImageDraw.Draw(sheet)
        pen.text((24,13),'PORTABLE LAPTOP GUIDE   /   FILE STUDY',font=fonts[17],fill=(19,106,105))
        pen.text((23,42),'The same cut in two files',font=fonts[40],fill=(21,45,57))
        pen.text((24,111),'Source   960 × 540',font=fonts[22],fill=(21,45,57))
        pen.text((502,111),'Proxy   480 × 270',font=fonts[22],fill=(21,45,57))
        for raw,x in zip(decoded,(24,502)):
            img=Image.frombytes('RGB',tile,raw[i*frame_size:(i+1)*frame_size])
            sheet.paste(img,(x,150))
        shot=max(index for index,cut in enumerate(cuts) if i>=cut)
        pen.text((24,421),f'Frame {i:03d}   /   Shot {chr(65+shot)}',font=fonts[28],fill=(21,45,57))
        pen.text((504,429),'Shot B starts at 48   ·   Shot C at 84',font=fonts[17],fill=(45,94,95))
        encoder.stdin.write(sheet.tobytes())
    encoder.stdin.close()
    if encoder.wait():
        raise RuntimeError('Comparison encoding failed')

results={'unicode_proof':proof(),'drawing_markup':drawings(),'video_proxy':clips(),
         'software':{'PyMuPDF':fitz.VersionBind,'ReportLab':reportlab.Version,'Pillow':PIL.__version__,
                     'FFmpeg':call(['ffmpeg','-version']).decode().splitlines()[0].split()[2],
                     'pdftotext':subprocess.run(['pdftotext','-v'],capture_output=True,text=True).stderr.splitlines()[0]}}
side_by_side()
(out/'results.json').write_text(json.dumps(results,ensure_ascii=False,indent=2)+'\n',encoding='utf-8')
print(json.dumps(results,ensure_ascii=False,indent=2))
