#!/usr/bin/env python3
"""Render a complete local source using the pinned native toolchain."""
import argparse,hashlib,json,os,re,shutil,subprocess,sys,tempfile
from pathlib import Path
from xml.etree import ElementTree as ET
from xml.sax.saxutils import escape

root=Path(__file__).resolve().parents[1]
cfg=json.loads((root/'config/render.json').read_text());kind=cfg['engine']
env=dict(os.environ,LC_ALL='C',LANG='C',SOURCE_DATE_EPOCH='0',FORCE_SOURCE_DATE='1',TZ='UTC')
def run(args,**kwargs):
    p=subprocess.run([str(a) for a in args],env=env,capture_output=True,**kwargs)
    if p.returncode:sys.exit(p.stderr.decode(errors='replace')+p.stdout.decode(errors='replace'))
    if str(args[0])=='grap' and re.search(rb'(?im)(?:syntax error|^Error near|^grap:)',p.stderr):
        sys.exit(p.stderr.decode(errors='replace'))
    if p.stderr.strip():sys.stderr.write(p.stderr.decode(errors='replace'))
    return p.stdout
def version():
    p=subprocess.run(['pdftocairo','-v'],capture_output=True,text=True,env=env)
    if 'version '+cfg['poppler'] not in p.stdout+p.stderr:sys.exit('Requires Poppler '+cfg['poppler'])
    if kind in {'pic','grap'}:
        if run(['gs','--version']).decode().strip()!=cfg['ghostscript']:sys.exit('Requires Ghostscript '+cfg['ghostscript'])
        if 'v'+cfg['pdfcrop'] not in run(['pdfcrop','--version']).decode():sys.exit('Requires pdfcrop '+cfg['pdfcrop'])
        for tool in ['pic','groff']:
            line=run([tool,'--version']).decode().splitlines()[0]
            if not line.endswith(' '+cfg['groff']):sys.exit('Requires GNU '+tool+' '+cfg['groff'])
        if kind=='grap':
            p=subprocess.run(['grap','--version'],capture_output=True,text=True,env=env)
            if not re.search(r'\bgrap '+re.escape(cfg['grap'])+r'\b',p.stdout+p.stderr):sys.exit('Requires grap '+cfg['grap'])
        return 'GNU pic / groff '+cfg['groff']+('; grap '+cfg['grap'] if kind=='grap' else '')
    rscript=os.environ.get('RSCRIPT') or shutil.which('Rscript') or '/opt/homebrew/opt/r/bin/Rscript'
    env['TOUR_R_LIBRARY']=os.environ.get('TOUR_R_LIBRARY',str(root/'.R-library'))
    records=json.loads((root/'config/packages.json').read_text())
    names='c('+','.join(json.dumps(r['package']) for r in records)+')'
    expression='.libPaths(c(Sys.getenv("TOUR_R_LIBRARY"),.libPaths()));cat(as.character(getRversion()),as.character(packageVersion("ggplot2")),intToUtf8(10));writeLines(vapply('+names+',function(p) packageDescription(p,fields="Version"),""))'
    lines=run([rscript,'--vanilla','-e',expression]).decode().strip().splitlines()
    output=lines[0].strip()
    if lines[1:]!=[r['version'] for r in records]:sys.exit('R dependency versions differ from config/packages.json')
    if output!=cfg['r']+' '+cfg['ggplot2']:sys.exit('Requires R '+cfg['r']+' and ggplot2 '+cfg['ggplot2']+'; found '+output)
    env['RSCRIPT']=rscript
    return 'R '+cfg['r']+'; ggplot2 '+cfg['ggplot2']
for relative,expected in cfg['asset_hashes'].items():
    if hashlib.sha256((root/relative).read_bytes()).hexdigest()!=expected:sys.exit('Reviewed asset changed: '+relative)
banner=version()
if sys.argv[1:]==['--version']:print(banner);sys.exit(0)
parser=argparse.ArgumentParser(description=__doc__);parser.add_argument('source',type=Path);args=parser.parse_args()
source=args.source;ident=source.stem
if not re.fullmatch(r'(?:PIC|GRA|GGP)-\d{2}-\d{3}',ident):sys.exit('Expected a tour example filename')
Path('figures').mkdir(exist_ok=True);native=Path('figures')/(ident+'.native.pdf');target=Path('figures')/(ident+'.pdf')
if kind in {'pic','grap'}:
    env['GROFF_FONT_PATH']=str(root/'assets/groff')
    text=source.read_bytes()
    if kind=='grap':text=run(['grap','-d','config/grap.defines'],input=text)
    text=run(['pic','-S'],input=text)
    native.write_bytes(run(['groff','-Tpdf','-P-e','-P-W','-P-pa3'],input=text))
    run(['pdfcrop','--hires','--margins','10',native,target])
    native.unlink()
else:
    with tempfile.TemporaryDirectory(prefix='ggplot2-fonts-') as temporary:
        conf=Path(temporary)/'fonts.conf'
        conf.write_text('<fontconfig><dir>'+escape(str(root/'assets/fonts'))+'</dir><cachedir>'+escape(temporary+'/cache')+'</cachedir></fontconfig>')
        env.update(FONTCONFIG_FILE=str(conf),PANGOCAIRO_BACKEND='fc',OPENBLAS_NUM_THREADS='1',OMP_NUM_THREADS='1',LC_ALL='en_US.UTF-8',LANG='en_US.UTF-8')
        run([env['RSCRIPT'],'--vanilla','-e','.libPaths(c(Sys.getenv("TOUR_R_LIBRARY"), .libPaths()));source(commandArgs(TRUE)[1])',source])
if not target.is_file():sys.exit('Native compiler did not produce '+str(target))
import pymupdf
with pymupdf.open(target) as pdf:
    if len(pdf)!=1 or not pdf[0].get_drawings():sys.exit('Expected one nonempty vector page')
    pdf.set_metadata({'title':ident,'creator':banner});pdf.set_xml_metadata('')
    # pdfcrop retains the source /Info dictionary in its imported PDF form.
    for xref in range(1,pdf.xref_length()):
        for key in ['CreationDate','ModDate']:
            if pdf.xref_get_key(xref,key)[0]!='null':pdf.xref_set_key(xref,key,'null')
    pdf.xref_set_key(-1,'ID','null')
    normalized=target.with_suffix('.normalized.pdf');pdf.save(normalized,garbage=4,deflate=True,no_new_id=True)
normalized.replace(target)
run(['pdftocairo','-svg',target,Path('figures')/(ident+'.svg')])
run(['pdftocairo','-png','-singlefile','-r','120',target,Path('figures')/ident])
svg=Path('figures')/(ident+'.svg');tree=ET.parse(svg);element=tree.getroot()
for node in element.iter():
    for key,value in node.attrib.items():
        if key.endswith('href') and not value.startswith(('#','data:')):sys.exit('External SVG resource')
element.set('role','img');element.set('aria-label',ident)
ET.register_namespace('','http://www.w3.org/2000/svg');ET.register_namespace('xlink','http://www.w3.org/1999/xlink')
tree.write(svg,encoding='utf-8',xml_declaration=True)
print(ident+': native PDF, SVG and PNG rendered with '+banner)
