"""Re-export saved ImageGen chapter-one masters through Aseprite; no generation."""
from pathlib import Path
import subprocess
import shutil
import json
ROOT=Path(__file__).resolve().parents[1]
ASEPRITE=shutil.which('aseprite') or str(Path.home()/'.local/bin/aseprite')
SRC=ROOT/'art/chapter1/source'
PORTRAITS=ROOT/'art/chapter1/portraits'
SPRITES=ROOT/'art/chapter1/sprites'
def run(script,**params):
 args=[ASEPRITE,'-b']
 for key,value in params.items(): args += ['--script-param',f'{key}={value}']
 args += ['--script',str(ROOT/'tools'/script)]
 result=subprocess.run(args,cwd=ROOT,capture_output=True,text=True)
 if result.returncode: raise RuntimeError(result.stdout+result.stderr)
selection=json.loads((ROOT/'content/chapter1/art_selection.json').read_text())
for character in selection.values():
 for entry in character['portraits']:
  source=SRC/(entry['source_stem']+'.png')
  output=ROOT/entry['file']
  if entry.get('alignment'):
   raw=PORTRAITS/(entry['source_stem']+'.png')
   run('export_portrait.lua',source=source,output=raw)
   alignment=entry['alignment']
   run('align_fishergirl_expression.lua',neutral=ROOT/alignment['neutral'],variant=raw,output=output,regions=alignment['regions'])
  elif entry.get('hair_black'):
   raw=PORTRAITS/(entry['source_stem']+'.png')
   run('export_portrait.lua',source=source,output=raw)
   run('recolor_ganoes_hair.lua',source=raw,output=output,limit=entry['hair_black'])
  else:
   run('export_portrait.lua',source=source,output=output)
 for entry in character['sprites']:
  stem=entry['source_stem']
  run('export_turnaround.lua',source=SRC/(stem+'.png'),boxes=SRC/(stem+'.boxes.lua'),height=entry['height'],output=ROOT/entry['file'])
subprocess.run(['python3',str(ROOT/'tools/build_chapter1_review.py')],cwd=ROOT,check=True)
