#!/usr/bin/env python3
"""Offline ditaa 0.11.0 driver; native Java renderer, one reviewed configuration."""
import argparse
import base64
import hashlib
import json
import os
from pathlib import Path
import subprocess
import sys

root=Path(__file__).resolve().parents[1]
config=json.loads((root/'config/render.json').read_text())
versions=json.loads((root/'VERSIONS.json').read_text())
jar=root/'tools/vendor/ditaa-0.11.0-standalone.jar'
font=root/config['font']
for path,expected in [(jar,versions['jar_sha256']),(font,versions['font_sha256'])]:
    if hashlib.sha256(path.read_bytes()).hexdigest()!=expected:
        sys.exit(f'Checksum mismatch: {path.name}')
java=os.getenv('JAVA','java')
check=subprocess.run([java,'-version'],capture_output=True,text=True,check=True)
if '11.0.33' not in check.stderr or '11.0.33+10' not in check.stderr:
    sys.exit('Reviewed renderer requires Java 11.0.33+10; select it with JAVA=/path/to/java')
command=[java,'-Djava.awt.headless=true','-Dfile.encoding=UTF-8','-Duser.language=en','-Duser.country=US','-jar',str(jar)]
if sys.argv[1:]==['--version']:
    print('ditaa 0.11.0 (upstream CLI banner: 0.11); Java 11.0.33+10');sys.exit(0)
if sys.argv[1:]==['--native-help']:
    sys.exit(subprocess.run(command+['--help']).returncode)
p=argparse.ArgumentParser(description=__doc__)
p.add_argument('--scale',type=float,default=config['scale'])
for flag in ['round-corners','transparent','no-antialias','no-separation','fixed-slope','debug','shadows']:
    p.add_argument('--'+flag,action='store_true')
p.add_argument('--background',default='FFFFFF')
p.add_argument('source',type=Path);p.add_argument('target',type=Path)
a=p.parse_args()
if not 0<a.scale<=4:p.error('Scale must be in (0, 4]')
if a.target.suffix not in {'.svg','.png'}:p.error('Target must end in .svg or .png')
args=['--overwrite','--encoding',config['encoding'],'--scale',str(a.scale),'--background',a.background]
if not (a.shadows or config['shadows']):args+=['--no-shadows']
for flag in ['round-corners','transparent','no-antialias','no-separation','fixed-slope','debug']:
    if getattr(a,flag.replace('-','_')):args+=['--'+flag]
if a.target.suffix=='.svg':
    args+=['--svg','--svg-font-url','data:font/ttf;base64,'+base64.b64encode(font.read_bytes()).decode()]
a.target.parent.mkdir(parents=True,exist_ok=True)
# subprocess uses a vector of arguments; no shell interpretation of diagram text.
result=subprocess.run(command+args+[str(a.source),str(a.target)],capture_output=True,text=True)
# Keep the native log readable: the binary font is already in the SVG.
import re
sys.stdout.write(re.sub(r'data:font/ttf;base64,[A-Za-z0-9+/=]+', '<embedded local Source Code Pro 2.042>', result.stdout))
sys.stderr.write(result.stderr)
sys.exit(result.returncode)
