"""Reproduce exact checks and genuine Squeak imageForm captures in a private image.
python run_native.py --vm /path/to/squeak --image /path/to/Squeak.image
"""
from pathlib import Path
import argparse, json, shutil, subprocess, tempfile
R=Path(__file__).resolve().parent
p=argparse.ArgumentParser()
p.add_argument('--vm',type=Path,required=True)
p.add_argument('--image',type=Path,required=True)
a=p.parse_args()
def q(text): return "'"+str(text).replace("'","''")+"'"
media=R/'native-media';media.mkdir(exist_ok=True)
for old in media.glob('lru*.png'): old.unlink()
cases=json.loads((R/'cases.json').read_text())['cases']
rows=[]
for c in cases:
 rows.append('{'+'. '.join([q(c['id']),q(c['code']),q(c['expectedExpression']),q(c.get('expectedPrintString','')),str(c['id'] in ['lru-01','lru-02']).lower()])+'}')
script='''| log ws window pane cases result expected source bundle demo snapshots expectedStates count button before |
log := FileStream forceNewFileNamed: LOG.
[World removeAllMorphs.
ws := Workspace new. window := ToolBuilder default open: ws.
window position: 20@20; extent: 1000@470.
pane := window allMorphs detect: [:m | m isKindOf: PluggableTextMorph].
pane setFont: (StrikeFont familyName: 'DejaVu Sans Mono' pointSize: 18).
cases := CASES.
cases do: [:c |
 source := c second.
 result := Compiler evaluate: source.
 expected := Compiler evaluate: c third.
 result = expected ifFalse: [Error signal: 'Wrong result for ', c first].
 c fourth isEmpty ifFalse: [result printString = c fourth ifFalse: [Error signal: 'Wrong printString for ', c first]].
 log nextPutAll: 'PASS '; nextPutAll: c first; nextPutAll: ' => '; nextPutAll: result printString; cr; flush.
 c fifth ifTrue: [
  ws contents: source. pane selectFrom: 1 to: source size. World doOneCycle.
  pane printIt. World doOneCycle.
  (pane text asString includesSubstring: result printString) ifFalse: [Error signal: 'Printed result missing'].
  PNGReadWriter putForm: window imageForm onFileNamed: MEDIA, c first, '.png']].
bundle := Compiler evaluate: (FileStream readOnlyFileNamed: BUNDLE) contentsOfEntireFile.
bundle = 30 ifFalse: [Error signal: 'Assertion bundle did not return 30'].
log nextPutAll: 'PASS standalone assertion bundle => 30'; cr; flush.
World removeAllMorphs.
source := (FileStream readOnlyFileNamed: VISUAL) contentsOfEntireFile.
demo := Compiler evaluate: source.
World doOneCycle.
PNGReadWriter putForm: demo first imageForm onFileNamed: MEDIA, 'lru-state-00.png'.
expectedStates := #((1 0 1 1 (6) 6 36 false nil) (2 0 2 2 (6 8) 8 64 false nil) (3 0 3 3 (6 8 10) 10 100 false nil) (4 1 3 3 (8 10 6) 6 36 true nil) (5 1 4 4 (10 6 12) 12 144 false 8) (6 2 4 4 (6 12 10) 10 100 true nil) (7 2 5 5 (12 10 8) 8 64 false 6) (8 3 5 5 (10 8 12) 12 144 true nil)).
count := 0.
button := demo first allMorphs detect: [:m | (m isKindOf: SimpleButtonMorph) and: [m label = 'Next request']].
expectedStates do: [:expectedState |
 button doButtonAction.
 result := demo fourth value.
 result = expectedState ifFalse: [Error signal: 'Visual trace mismatch ', result printString].
 count := count + 1. World doOneCycle.
 PNGReadWriter putForm: demo first imageForm onFileNamed: MEDIA, 'lru-state-', (count printString padded: #left to: 2 with: $0), '.png'.
 log nextPutAll: 'PASS visual state '; nextPutAll: result printString; cr; flush].
before := demo fourth value. button doButtonAction.
demo fourth value = before ifFalse: [Error signal: 'Final Next must be a no-op'].
button := demo first allMorphs detect: [:m | (m isKindOf: SimpleButtonMorph) and: [m label = 'Reset']].
button doButtonAction.
demo fourth value = #(0 0 0 0 () nil nil false nil) ifFalse: [Error signal: 'Reset mismatch'].
log nextPutAll: 'PASS Next after final request and Reset button'; cr.
demo first delete.
log nextPutAll: 'COMPLETE: 10 exact cases, 30-assertion standalone bundle, 8 visual states and 2 control checks'; cr]
on: Error do: [:error | log nextPutAll: 'ERROR '; nextPutAll: error printString; cr; nextPutAll: error signalerContext longStack].
log close. Smalltalk snapshot: false andQuit: true.
'''
script=script.replace('CASES','{'+'. '.join(rows)+'}')
for key,value in [('LOG',R/'native-results.txt'),('MEDIA',str(media)+'/'),('BUNDLE',R/'lru-cache.st'),('VISUAL',R/'lru-visual-trace.st')]:
 script=script.replace(key,q(value))
with tempfile.TemporaryDirectory(prefix='learnsqueak-lru-') as name:
 d=Path(name);image=d/'LRU.image';shutil.copy2(a.image,image)
 if a.image.with_suffix('.changes').exists():shutil.copy2(a.image.with_suffix('.changes'),image.with_suffix('.changes'))
 for src in a.image.parent.glob('*.sources'):(d/src.name).symlink_to(src.resolve())
 runner=d/'run.st';runner.write_text(script)
 result=subprocess.run([str(a.vm.resolve()),'-vm-display-null','-vm-sound-null',str(image),str(runner)],capture_output=True,text=True,timeout=90,cwd=d)
 (R/'vm-output.txt').write_text(result.stdout+result.stderr)
 result.check_returncode()
report=(R/'native-results.txt').read_text();print(report)
assert 'ERROR' not in report and 'COMPLETE:' in report,report
