#!/usr/bin/env python3
"""Host-compatible Pandoc executable with a durable, science-neutral layout pass.

JSON capability probes pass through unchanged. Only LaTeX output is transformed.
Choose the installed Pandoc through PREREG_REAL_PANDOC (default /usr/bin/pandoc).
"""
from pathlib import Path
import os,subprocess,sys,re
args=sys.argv[1:];real=os.environ.get('PREREG_REAL_PANDOC','/usr/bin/pandoc')
if Path(real).resolve()==Path(__file__).resolve():raise SystemExit('Recursive Pandoc configuration')
out=None
for i,a in enumerate(args):
 if a in ('-o','--output') and i+1<len(args):out=args[i+1]
 elif a.startswith('--output='):out=a.split('=',1)[1]
latex=any(a in ('--to=latex','-tlatex') for a in args) or any(args[i] in ('--to','-t') and args[i+1]=='latex' for i in range(len(args)-1)) or bool(out and out.endswith('.tex'))
if latex and out and 'prereg' in Path(out).name:
 for i,a in enumerate(args):
  if a.startswith('--from='):args[i]=a+'-tex_math_dollars'
  elif a in ('--from','-f') and i+1<len(args):args[i+1]+='-tex_math_dollars'
if latex:args+=['--lua-filter='+str(Path(__file__).with_name('layout.lua'))]
r=subprocess.run([real,*args],stdout=subprocess.PIPE if latex else None)
if r.returncode:raise SystemExit(r.returncode)
if latex:
 text=Path(out).read_text() if out else r.stdout.decode()
 # longtable supports starred captions; preserve the authored Table identifiers.
 def table_layout(m):
  block=m[0].replace('\\caption{','\\caption*{')
  caption=re.search(r'\\caption\*\{(.*?)\}\\tabularnewline',block,re.S)
  if caption:
   block=block.replace('\\endfirsthead\n\\toprule','\\endfirsthead\n\\caption*{'+caption[1]+' (continued)}\\tabularnewline\n\\toprule',1)
  return block
 text=re.sub(r'\\begin\{longtable\}.*?\\end\{longtable\}',table_layout,text,flags=re.S)
 # The authored Figure IDs are scientific display bindings, independent of appearance order.
 def figure_layout(m):
  block=m[0]
  if '\\caption{' in block:
   block=block.replace('\\caption{',r'\begingroup\makeatletter\long\def\@figurecaption#1#2{\figurecaptionfont #2\par}\makeatother\caption{',1)
   block=block.replace('\\end{figure}',r'\endgroup'+'\n'+r'\end{figure}')
  return block
 text=re.sub(r'\\begin\{figure\}.*?\\end\{figure\}',figure_layout,text,flags=re.S)
 if out:Path(out).write_text(text)
 else:sys.stdout.write(text)
