"""Re-run exact lesson answers and capture genuine native Squeak Morphic states.
Supply --vm path/to/bin/squeak and --image path/to/Squeak.image.
The original image is never saved or edited; this script uses a private copy.
"""
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)
p.add_argument('--media',type=Path,default=R/'native-media')
a=p.parse_args()
a.media=a.media.resolve(); a.media.mkdir(parents=True,exist_ok=True)
for old in a.media.glob('merging-intervals-*.png'): old.unlink()
q=lambda s: "'"+str(s).replace("'","''")+"'"
cases=json.loads((R/'merging-intervals-cases.json').read_text())['cases']
items=[]
for c in cases:
    items.append('{'+'. '.join([q(c['id']),q(c['code']),q(c['expectedExpression']), 'true' if c.get('capture') else 'false'])+'}')
source='''| log ws window pane cases result expected source assertionCount view visualization |
log := FileStream forceNewFileNamed: %s.
[World removeAllMorphs.
ws := Workspace new. window := ToolBuilder default open: ws.
window position: 30@30; extent: 1000@550.
pane := window allMorphs detect: [:m | m isKindOf: PluggableTextMorph].
pane setFont: (StrikeFont familyName: 'DejaVu Sans Mono' pointSize: 18).
cases := {%s}.
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, ': ', result printString].
 log nextPutAll: 'PASS '; nextPutAll: c first; nextPutAll: ' => '; nextPutAll: result printString; cr; flush.
 c fourth 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: 'Print it answer missing'].
 PNGReadWriter putForm: window imageForm onFileNamed: %s, c first, '.png']].
assertionCount := Compiler evaluate: (FileStream readOnlyFileNamed: %s) contentsOfEntireFile.
assertionCount = 13 ifFalse: [Error signal: 'Expected thirteen assertions'].
log nextPutAll: 'ASSERTIONS '; nextPutAll: assertionCount printString; cr; flush.
"Keep the modified Workspace alive; closing it would ask for confirmation."
visualization := (FileStream readOnlyFileNamed: %s) contentsOfEntireFile.
1 to: 6 do: [:stage |
 source := visualization copyReplaceAll: 'stage := 1.' with: 'stage := ', stage printString, '.'.
 log nextPutAll: 'START visual '; nextPutAll: stage printString; cr; flush.
 view := Compiler evaluate: source.
 log nextPutAll: 'CREATED visual '; nextPutAll: stage printString; cr; flush.
 World doOneCycle.
 PNGReadWriter putForm: view imageForm onFileNamed: %s, 'merging-intervals-trace-', stage printString, '.png'.
 view delete.
 log nextPutAll: 'CAPTURE trace '; nextPutAll: stage printString; cr].
log nextPutAll: 'COMPLETE'; cr]
on: Error do: [:e | log nextPutAll: 'ERROR '; nextPutAll: e printString; cr; nextPutAll: e signalerContext longStack].
log close. Smalltalk snapshot: false andQuit: true.
''' % (q(R/'native-results.txt'), '. '.join(items), q(str(a.media)+'/'), q(R/'merging-intervals.st'), q(R/'visual-trace.st'),q(str(a.media)+'/'))
with tempfile.TemporaryDirectory(prefix='merging-native-',dir='/tmp') as td:
    t=Path(td); image=t/'Private.image'
    shutil.copy2(a.image,image)
    changes=a.image.with_suffix('.changes')
    if changes.exists(): shutil.copy2(changes,t/'Private.changes')
    for f in a.image.parent.glob('*.sources'): (t/f.name).symlink_to(f.resolve())
    runner=t/'run.st'; runner.write_text(source)
    completed=subprocess.run([str(a.vm.resolve()),'-vm-display-null','-vm-sound-null',str(image),str(runner)],capture_output=True,text=True,timeout=90)
    (R/'vm-output.txt').write_text(completed.stdout+completed.stderr)
    completed.check_returncode()
report=(R/'native-results.txt').read_text()
print(report)
assert report.rstrip().endswith('COMPLETE'),report
