"""Prepare the supplied legal-person artwork; production needs PHP only."""
import hashlib, io, json, re, sys
from pathlib import Path
from pypdf import PdfReader, PdfWriter
from pypdf.generic import NameObject, DictionaryObject, ArrayObject, DecodedStreamObject
from pypdf._codecs.core_font_metrics import CORE_FONT_METRICS

source = Path(sys.argv[1])
destination = Path(__file__).resolve().parents[1] / 'resources/pdf'
reader = PdfReader(source)
assert len(reader.pages) == 1 and len(reader.pages[0]['/Annots']) == 153
rects = [[float(v) for v in a.get_object()['/Rect']] for a in reader.pages[0]['/Annots']]
writer = PdfWriter()
writer.add_page(reader.pages[0])
page = writer.pages[0]
del page['/Annots']
font = writer._add_object(DictionaryObject({NameObject('/Type'):NameObject('/Font'), NameObject('/Subtype'):NameObject('/Type1'), NameObject('/BaseFont'):NameObject('/Helvetica'), NameObject('/Encoding'):NameObject('/WinAnsiEncoding')}))
page['/Resources']['/Font'][NameObject('/FilledFont')] = font
before = DecodedStreamObject(); before.set_data(b'q\n')
after = DecodedStreamObject(); after.set_data(b'\nQ\n')
original = page.raw_get('/Contents')
page[NameObject('/Contents')] = ArrayObject([writer._add_object(before), *(original if isinstance(original, ArrayObject) else [original]), writer._add_object(after)])
path = destination / 'legal-client-template.pdf'
writer.write(path)
pdf = path.read_bytes()
parsed = PdfReader(path)
page = parsed.pages[0]
parent = page.raw_get('/Parent').idnum
contents = page.raw_get('/Contents')
page[NameObject('/Contents')] = ArrayObject([*contents] if isinstance(contents, ArrayObject) else [contents])
buffer = io.BytesIO(); page.write_to_stream(buffer)
widths = CORE_FONT_METRICS['Helvetica'].character_widths
manifest = {'source_sha256':hashlib.sha256(source.read_bytes()).hexdigest(), 'template_sha256':hashlib.sha256(pdf).hexdigest(), 'rects':rects, 'page_dictionary':buffer.getvalue().decode('latin1'), 'pages_id':parent, 'root_id':parsed.trailer.raw_get('/Root').idnum, 'size':parsed.trailer['/Size'], 'previous_xref':int(re.search(rb'startxref\s+(\d+)\s+%%EOF\s*$',pdf)[1]), 'widths':{str(i):widths.get(bytes([i]).decode('cp1252',errors='replace'),556) for i in range(256)}}
(destination / 'legal-client-template.json').write_text(json.dumps(manifest,ensure_ascii=False,indent=2),encoding='utf-8')
print('Prepared legal template with',len(rects),'field positions')
