#!/usr/bin/env python3
"""Read trusted pinned engine defaults, preserving every direct-PDF option."""
from pathlib import Path
import argparse,gzip,hashlib,json,re,xml.etree.ElementTree as E
p=argparse.ArgumentParser();p.add_argument('--core',type=Path,required=True);a=p.parse_args();root=Path.cwd();out=Path(__file__).parent;sha=lambda b:hashlib.sha256(b).hexdigest();fonts=root/'third_party/office/26.2-fc03117-fonts2'
meta=json.loads(gzip.decompress((fonts/'runtime/soffice.data.js.metadata.gz').read_bytes()));entry=next(f for f in meta['files']if f['filename']=='/instdir/share/registry/main.xcd');raw=gzip.decompress((fonts/'runtime/soffice.data.gz').read_bytes());assert sha(raw)==json.loads((fonts/'runtime-integrity.json').read_text())['soffice.data']['sha256'];xcd=raw[entry['start']:entry['end']];key='{http://openoffice.org/2001/registry}name';defaults={}
def walk(e,path=[]):
 name=e.get(key);path=path+([name]if name else[])
 if path[:4]==['Common','Filter','PDF','Export']and len(path)==5:
  values=[c for c in e if c.tag.endswith('value')]
  if values:assert name not in defaults;defaults[name]=''.join(values[0].itertext())
 for c in e:walk(c,path)
walk(E.fromstring(xcd));source=(a.core/'filter/source/pdf/pdffilter.cxx').read_bytes();block=source.decode().split('if ( !aFilterData.hasElements() )',1)[1].split('aFilterData = aCfgItem.GetFilterData();',1)[0];options={};before={}
for kind,name,fallback in re.findall(r'aCfgItem.Read(Bool|Int32)\(\s*u"([^"]+)"_ustr,\s*([\w-]+)\s*\)',block):
 fallback={'DefaultPDFJPEGQuality':'90','DefaultPDFImageDPI':'300'}.get(fallback,fallback);value=defaults.get(name,fallback);assert value in ['true','false']if kind=='Bool'else re.fullmatch(r'-?\d+',value)
 before[name]=dict(type='boolean'if kind=='Bool'else'long',value=value)
assert len(before)==39,len(before)
options={k:dict(v)for k,v in before.items()};options['UseLosslessCompression']['value']='true';options['ReduceImageResolution']['value']='false';assert options['UseTaggedPDF']['value']=='true'and options['InitialView']['value']=='1'
(out/'office-pdf-options.js').write_text('// Trusted static export options. Reproduce with pin-office-pdf-options.py.\nconst officePinnedPdfOptions='+json.dumps(options,separators=(',',':'))+';\n')
(out/'office-pdf-options-provenance.json').write_text(json.dumps(dict(producerSha256=sha(Path(__file__).read_bytes()),nativeCommit='fc03117d3f8f2d7137d973e5db3b2514e8eba990',nativePdfFilterPath='filter/source/pdf/pdffilter.cxx',nativePdfFilterSha256=sha(source),configPath='/instdir/share/registry/main.xcd',configSha256=sha(xcd),dataSha256=sha(raw),before=before,after=options,changed=[k for k in before if before[k]!=options[k]],method='All39 direct-export configuration reads from the exact native3 source are preserved using the unchanged trusted fonts2 data registry. Missing configuration values use native source fallbacks. Only lossless image compression/resolution reduction are overridden; no user file/profile/options enter this data. Complete native sources and delivered data remain in the existing source offers.'),indent=2)+'\n');print(json.dumps(dict(options=len(options),changed=[k for k in before if before[k]!=options[k]])))
