File size: 242,428 Bytes
f27460e
9328e91
94b8cb6
932fd0e
4a5b186
9328e91
 
 
 
43647c4
cce05a1
 
a69d738
 
 
 
 
 
 
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
932fd0e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
cce05a1
 
a69d738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198db95
4a5b186
a69d738
 
 
9328e91
a69d738
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
9328e91
 
 
a69d738
9328e91
 
 
 
a69d738
 
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
 
4a5b186
 
f27460e
9328e91
 
 
 
 
 
 
 
 
a69d738
9328e91
a69d738
 
9328e91
 
 
a69d738
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
9328e91
 
 
 
 
a69d738
9328e91
 
 
 
 
 
 
 
a69d738
9328e91
 
 
 
a69d738
9328e91
 
 
a69d738
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
9328e91
 
 
 
 
 
 
 
 
 
 
 
a69d738
9328e91
 
 
 
 
 
 
 
 
 
ee7fb1c
9328e91
 
 
 
 
 
 
 
a69d738
9328e91
a69d738
 
9328e91
 
 
 
 
 
 
 
 
a69d738
9328e91
 
 
a69d738
 
 
 
 
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
198db95
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a7677d
9328e91
 
a69d738
9328e91
a69d738
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33582fc
a69d738
 
9328e91
a69d738
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
 
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
 
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
 
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
 
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
9328e91
a69d738
9328e91
 
 
 
 
 
 
 
a69d738
9328e91
 
 
a69d738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62da353
a69d738
 
 
62da353
a69d738
62da353
a69d738
62da353
a69d738
62da353
a69d738
f9b9206
a69d738
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9328e91
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a69d738
 
9328e91
 
a69d738
9328e91
 
 
 
 
 
 
 
 
f27460e
9328e91
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
import gradio as gr
import spaces
import json
import textwrap
from gradio_client import Client
import os
import requests
from huggingface_hub import InferenceClient
from openai import OpenAI

#Imported Long Variables - comment for each move to search
from relatively_constant_variables import *
from leveraging_machine_learning import *
from jsconfig_idea_support import *
from timeline_and_UI_generation_functions import *
from my_text_game_engine_attempt import *
from file_explorer_and_upload import *
from state_prompt_fileman_UI_functions import *
from ui_gr_media_management import *
from timeline_narrative_construction_tools import *
from bible_as_inspiration_source import *
from config_linting import (
    validate_branching, generate_story_flags, generate_mermaid_diagram,
    get_config_health_summary, get_llm_cohesion_prompts,
    get_validation_with_fixes, apply_all_quick_fixes, format_issues_for_display,
    get_state_issues_map
)
from timeline_and_UI_generation_functions import (
    NARRATIVE_TEMPLATES, get_narrative_templates_list,
    generate_config_from_template, generate_config_from_prompt
)
from my_text_game_engine_attempt import (
    get_all_states_from_config, jump_to_state, hot_reload_config,
    get_current_state_id, make_choice_with_state_display, export_playthrough_log,
    get_initgameinfo, get_path_errors
)
from ui_tabs.big_rpg_scale_tab import EntityDatabase

# LinPEWFprevious_messages = []

# FILM_SCENARIOS and generate_scenario_sequence moved to film_scenarios.py

# ==================== DEMO CONFIGS ====================
SANDWICH_DEMO_CONFIG = {
    "game_start": {
        "intro": {
            "description": "**Sandwich Quest**\n\nYou're hungry! Time to get a sandwich from Tony's shop.",
            "choices": ["Start adventure"],
            "transitions": {"Start adventure": "home/start"},
            "on_enter": {"set_money": 20, "start_mission": "get_lunch"}
        }
    },
    "home": {
        "start": {
            "description": "**Your Home**\n\nYour stomach growls. The fridge is empty.\n\nYou have 20 gold.",
            "choices": ["Go outside", "Check wallet"],
            "transitions": {"Go outside": "street/arrive", "Check wallet": "home/wallet"}
        },
        "wallet": {
            "description": "You check your wallet. **20 gold** - enough for a sandwich!",
            "choices": ["Go outside"],
            "transitions": {"Go outside": "street/arrive"}
        }
    },
    "street": {
        "arrive": {
            "description": "**Main Street**\n\nPeople walk by. You see Tony's Sandwich Shop ahead.\n\nMrs. Jenkins waves at you.",
            "choices": ["Enter sandwich shop", "Talk to Mrs. Jenkins", "Go home"],
            "transitions": {
                "Enter sandwich shop": "sandwich_shop/arrive",
                "Talk to Mrs. Jenkins": "street/jenkins",
                "Go home": "home/start"
            }
        },
        "jenkins": {
            "description": "**Mrs. Jenkins** smiles.\n\n\"Hello dear! Getting lunch? Tony makes the best sandwiches!\"",
            "choices": ["Thanks for the tip!", "Goodbye"],
            "transitions": {"Thanks for the tip!": "street/arrive", "Goodbye": "street/arrive"}
        }
    },
    "sandwich_shop": {
        "arrive": {
            "description": "**Tony's Sandwich Shop**\n\nThe smell of fresh bread fills the air.\n\n**Tony** stands behind the counter.\n\n*Quest objective reached!*",
            "choices": ["Talk to Tony", "Look at menu", "Leave"],
            "transitions": {
                "Talk to Tony": "sandwich_shop/tony",
                "Look at menu": "sandwich_shop/menu",
                "Leave": "street/arrive"
            },
            "on_enter": {"set_flag": "reached_sandwich_shop"}
        },
        "menu": {
            "description": "**Menu:**\n- Classic Sandwich: 5 gold\n- Deluxe Sandwich: 10 gold\n- Super Sandwich: 15 gold",
            "choices": ["Talk to Tony", "Leave"],
            "transitions": {"Talk to Tony": "sandwich_shop/tony", "Leave": "street/arrive"}
        },
        "tony": {
            "description": "**Tony** grins.\n\n\"What can I get you today?\"",
            "choices": ["Buy Classic (5g)", "Buy Deluxe (10g)", "Just looking"],
            "transitions": {
                "Buy Classic (5g)": "sandwich_shop/buy_classic",
                "Buy Deluxe (10g)": "sandwich_shop/buy_deluxe",
                "Just looking": "sandwich_shop/arrive"
            }
        },
        "buy_classic": {
            "description": "You hand over 5 gold.\n\nTony gives you a **Classic Sandwich**!\n\n*Quest complete!*",
            "choices": ["Eat it!", "Save for later"],
            "transitions": {"Eat it!": "sandwich_shop/eat", "Save for later": "street/arrive"},
            "on_enter": {"remove_money": 5, "add_item": "Classic Sandwich", "complete_mission": "get_lunch"}
        },
        "buy_deluxe": {
            "description": "You hand over 10 gold.\n\nTony gives you a **Deluxe Sandwich**!\n\n*Quest complete!*",
            "choices": ["Eat it!", "Save for later"],
            "transitions": {"Eat it!": "sandwich_shop/eat", "Save for later": "street/arrive"},
            "on_enter": {"remove_money": 10, "add_item": "Deluxe Sandwich", "complete_mission": "get_lunch"}
        },
        "eat": {
            "description": "Mmm! Delicious!\n\n**THE END**\n\nThanks for playing!",
            "choices": ["Play again"],
            "transitions": {"Play again": "game_start/intro"}
        }
    }
}

SKYRIM_DEMO_CONFIG = {
    "game_start": {
        "intro": {
            "description": "**Welcome, Dragonborn!**\n\nYour journey begins. You have 100 gold.\n\n*Main quest: Unbound has started.*",
            "choices": ["Begin adventure"],
            "transitions": {"Begin adventure": "whiterun/arrive"},
            "on_enter": {"set_money": 100, "start_mission": ["mq101", "mq102"]}
        }
    },
    "whiterun": {
        "arrive": {
            "description": "**Whiterun** (Whiterun Hold)\n\nA bustling city of 200 souls. The streets are alive with activity.\n\nYou see: Belethor the Merchant.",
            "choices": ["Speak with Belethor", "Browse Belethor's wares", "Travel to Riverwood", "Travel to Dragonsreach", "Check quest journal"],
            "transitions": {
                "Speak with Belethor": "whiterun/talk_belethor",
                "Browse Belethor's wares": "whiterun/shop",
                "Travel to Riverwood": "riverwood/arrive",
                "Travel to Dragonsreach": "dragonsreach/arrive",
                "Check quest journal": "quest_journal/journal"
            }
        },
        "talk_belethor": {
            "description": "**Belethor** greets you.\n\n\"Everything's for sale, my friend. Everything. If I had a sister, I'd sell her in a second.\"",
            "choices": ["What do you have?", "Goodbye"],
            "transitions": {"What do you have?": "whiterun/shop", "Goodbye": "whiterun/arrive"}
        },
        "shop": {
            "description": "**Belethor's General Goods**\n\n- Iron Sword (25g)\n- Health Potion (25g)\n- Leather Strips (3g)",
            "choices": ["Buy Iron Sword", "Buy Health Potion", "Leave"],
            "transitions": {
                "Buy Iron Sword": "whiterun/buy_sword",
                "Buy Health Potion": "whiterun/buy_potion",
                "Leave": "whiterun/arrive"
            }
        },
        "buy_sword": {
            "description": "You purchase an **Iron Sword** for 25 gold.",
            "choices": ["Continue shopping", "Leave"],
            "transitions": {"Continue shopping": "whiterun/shop", "Leave": "whiterun/arrive"},
            "on_enter": {"remove_money": 25, "add_item": "Iron Sword"}
        },
        "buy_potion": {
            "description": "You purchase a **Health Potion** for 25 gold.",
            "choices": ["Continue shopping", "Leave"],
            "transitions": {"Continue shopping": "whiterun/shop", "Leave": "whiterun/arrive"},
            "on_enter": {"remove_money": 25, "add_item": "Health Potion"}
        }
    },
    "riverwood": {
        "arrive": {
            "description": "**Riverwood** (Whiterun Hold)\n\nA quiet village of 50 people. Life here is simple.\n\nYou see: Alvor the Blacksmith.\n\n*Quest objective: Escape to Riverwood - Complete!*",
            "choices": ["Speak with Alvor", "Travel to Whiterun", "Enter Bleak Falls Barrow", "Check quest journal"],
            "transitions": {
                "Speak with Alvor": "riverwood/talk_alvor",
                "Travel to Whiterun": "whiterun/arrive",
                "Enter Bleak Falls Barrow": "bleak_falls/arrive",
                "Check quest journal": "quest_journal/journal"
            },
            "on_enter": {"set_flag": "reached_riverwood", "set_knowledge": {"last_location": "riverwood"}}
        },
        "talk_alvor": {
            "description": "**Alvor** looks up from his forge.\n\n\"You're the one who escaped Helgen? By the Nine! Come, tell me what happened.\"\n\n*Quest updated: Spoke with Alvor*",
            "choices": ["Tell him about the dragon", "Ask about Bleak Falls", "Goodbye"],
            "transitions": {
                "Tell him about the dragon": "riverwood/dragon_talk",
                "Ask about Bleak Falls": "riverwood/bleak_falls_info",
                "Goodbye": "riverwood/arrive"
            },
            "on_enter": {"set_flag": "talked_alvor"}
        },
        "dragon_talk": {
            "description": "Alvor's face pales.\n\n\"A dragon? Are you sure? We need to warn Jarl Balgruuf in Dragonsreach!\"",
            "choices": ["I'll go warn him", "Maybe later"],
            "transitions": {"I'll go warn him": "whiterun/arrive", "Maybe later": "riverwood/arrive"}
        },
        "bleak_falls_info": {
            "description": "\"Bleak Falls Barrow? That old ruin? Nothing but draugr and bandits up there. But I've heard the court wizard is looking for something from that place.\"",
            "choices": ["Thanks", "Goodbye"],
            "transitions": {"Thanks": "riverwood/arrive", "Goodbye": "riverwood/arrive"}
        }
    },
    "dragonsreach": {
        "arrive": {
            "description": "**Dragonsreach** (Whiterun Hold)\n\nThe great hall of the Jarl. Guards watch your every move.\n\nYou see: Jarl Balgruuf on his throne.",
            "choices": ["Speak with Jarl Balgruuf", "Leave"],
            "transitions": {
                "Speak with Jarl Balgruuf": "dragonsreach/talk_balgruuf",
                "Leave": "whiterun/arrive"
            }
        },
        "talk_balgruuf": {
            "description": "**Jarl Balgruuf** regards you from his throne.\n\n\"What brings you to Dragonsreach?\"\n\n*Quest updated: Spoke with the Jarl*",
            "choices": ["I bring news of the dragon attack", "I seek work", "Farewell"],
            "transitions": {
                "I bring news of the dragon attack": "dragonsreach/dragon_news",
                "I seek work": "dragonsreach/work",
                "Farewell": "dragonsreach/arrive"
            },
            "on_enter": {"set_flag": "talked_balgruuf"}
        },
        "dragon_news": {
            "description": "The Jarl leans forward.\n\n\"A dragon? This is grave news indeed. Speak to my court wizard, Farengar. He has been researching dragons.\"\n\n*Quest: Before the Storm progressed*",
            "choices": ["I'll speak to Farengar", "Where is Farengar?"],
            "transitions": {
                "I'll speak to Farengar": "dragonsreach/farengar",
                "Where is Farengar?": "dragonsreach/farengar"
            }
        },
        "work": {
            "description": "\"Work? Perhaps. The Companions are always looking for strong arms. Speak to Kodlak at Jorrvaskr.\"",
            "choices": ["Thank you"],
            "transitions": {"Thank you": "dragonsreach/arrive"}
        },
        "farengar": {
            "description": "**Farengar Secret-Fire** looks up from his books.\n\n\"Ah, the Jarl's new errand person. I need you to fetch something from Bleak Falls Barrow - a stone tablet called the Dragonstone.\"\n\n*New quest: Bleak Falls Barrow*",
            "choices": ["I'll get it", "Tell me more about the Dragonstone"],
            "transitions": {
                "I'll get it": "dragonsreach/arrive",
                "Tell me more about the Dragonstone": "dragonsreach/dragonstone_info"
            },
            "on_enter": {"start_mission": "mq103"}
        },
        "dragonstone_info": {
            "description": "\"It's an ancient map of dragon burial sites. If the dragons are truly returning, we need to know where they might appear.\"",
            "choices": ["I'll retrieve it"],
            "transitions": {"I'll retrieve it": "dragonsreach/arrive"}
        }
    },
    "bleak_falls": {
        "arrive": {
            "description": "**Bleak Falls Barrow** (Whiterun Hold)\n\nAncient stone corridors stretch into darkness. Danger lurks in every shadow.\n\n*This is the destination of your quest!*",
            "choices": ["Explore deeper", "Leave"],
            "transitions": {
                "Explore deeper": "bleak_falls/explore",
                "Leave": "riverwood/arrive"
            },
            "on_enter": {"set_flag": "reached_bleak_falls"}
        },
        "explore": {
            "description": "You venture into the barrow. Cobwebs and ancient dust fill the air.\n\nYou hear shuffling in the darkness...\n\n*A draugr emerges!*",
            "choices": ["Fight!", "Retreat!"],
            "transitions": {
                "Fight!": "bleak_falls/combat",
                "Retreat!": "bleak_falls/arrive"
            }
        },
        "combat": {
            "description": "You strike down the draugr!\n\nDeeper in, you find a chamber with an ancient wall... and the **Dragonstone**!",
            "choices": ["Take the Dragonstone", "Examine the wall"],
            "transitions": {
                "Take the Dragonstone": "bleak_falls/get_stone",
                "Examine the wall": "bleak_falls/word_wall"
            }
        },
        "word_wall": {
            "description": "Strange words glow on the wall... You feel power flowing into you.\n\n*You learned a Word of Power: FUS (Force)*",
            "choices": ["Take the Dragonstone"],
            "transitions": {"Take the Dragonstone": "bleak_falls/get_stone"},
            "on_enter": {"set_flag": "learned_fus"}
        },
        "get_stone": {
            "description": "You take the **Dragonstone**!\n\n*Quest updated: Return to Farengar*",
            "choices": ["Return to Dragonsreach"],
            "transitions": {"Return to Dragonsreach": "dragonsreach/arrive"},
            "on_enter": {"add_item": "Dragonstone", "set_flag": "has_dragonstone"}
        }
    },
    "quest_journal": {
        "journal": {
            "description": "**Quest Journal**\n\n**Main Quests:**\n- Unbound: Escape to Riverwood\n- Before the Storm: Speak to the Jarl\n- Bleak Falls Barrow: Retrieve the Dragonstone",
            "choices": ["Travel to Riverwood", "Travel to Dragonsreach", "Close journal"],
            "transitions": {
                "Travel to Riverwood": "riverwood/arrive",
                "Travel to Dragonsreach": "dragonsreach/arrive",
                "Close journal": "whiterun/arrive"
            }
        }
    }
}

def add_scenario_prompts_to_queue(prompts_text, media_type="image"):
    """Add generated prompts to the generation queue.

    Args:
        prompts_text: Text containing prompts (one per line starting with 'Cinematic shot:')
        media_type: Type of media to generate ('image', 'audio', '3d', 'tts')
    """
    global generation_queue
    if not prompts_text or not prompts_text.strip():
        return get_queue_dataframe(), f"**Queue: {len(generation_queue)} items**", "No prompts to add"

    lines = prompts_text.strip().split("\n")
    added = 0
    for line in lines:
        line = line.strip()
        # Skip header lines and empty lines
        if not line or line.startswith("##") or line.startswith("#"):
            continue
        # Accept lines starting with "Cinematic shot:" or any non-empty line
        if line.startswith("Cinematic shot:") or (len(line) > 10 and not line.startswith("Video Prompts")):
            item = {
                "id": len(generation_queue) + 1,
                "type": media_type,  # Use image type since video isn't supported yet
                "prompt": line.strip(),
                "status": "pending"
            }
            generation_queue.append(item)
            added += 1

    return get_queue_dataframe(), f"**Queue: {len(generation_queue)} items**", f"Added {added} {media_type} prompts to queue"

def LinPEWFformat_prompt(current_prompt, prev_messages):
    formatted_prompt = textwrap.dedent("""
    Previous prompts and responses:
    {history}
    
    Current prompt:
    {current}
    
    Please respond to the current prompt, taking into account the context from previous prompts and responses.
    """).strip()
    
    history = "\n\n".join(f"Prompt {i+1}: {msg}" for i, msg in enumerate(prev_messages))
    return formatted_prompt.format(history=history, current=current_prompt)

#-----------------------------------------------------------------------------------------------------------------------------------

def TestGradioClientrandommodel(text):
    try:
        # client = Client("Qwen/Qwen2-72B-Instruct")
        # result = client.predict(
        #         query=text, #"Hello!!",
        #         history=[],
        #         system="You are a helpful assistant.",
        #         api_name="/model_chat"
        # )
        
        client = Client("huggingface-projects/gemma-2-9b-it")
        result = client.predict(
                message=text, #"Hello!!",
                max_new_tokens=1024,
                temperature=0.6,
                top_p=0.9,
                top_k=50,
                repetition_penalty=1.2,
                api_name="/chat"
        )
        #print(result)

        #print(result[1][0]) #All messages in the conversation
        #print(result[2]) # System prompt
    except Exception as e:
        result = str(e) 
    return result #result[1][0][1] # If supporting conversations this needs to return the last message instead

#-----=------------------=--------------------=--------------------=----------------------=----


ConfigConversionforExporttoPlatformselector = gr.Dropdown(choices=["playcanvas", "godot", "unreal", "gamemaker", "flutter", "2d map related space", "existing game"])

# Import platform exporters
from playcanvas_exporter import export_to_playcanvas
from godot_exporter import export_to_godot
from unreal_exporter import export_to_unreal

# Import LLM playtester
from llm_playtester import run_llm_playtest

# Import platform exporters package
from exporters import ConfigConversionforExporttoPlatform

# Import film scenarios and JSON utilities
from film_scenarios import FILM_SCENARIOS, generate_scenario_sequence
from beat_scenarios import STORY_BEATS, generate_beat_sequence
from dnd_scenarios import DND_ENCOUNTERS, generate_dnd_sequence
from world_scenarios import WORLD_LOCATIONS, generate_world_sequence
from timeline_scenarios import TIMELINE_EVENTS, generate_timeline_sequence
from song_scenarios import EMOTIONAL_STATES, generate_song_sequence
from mystery_scenarios import MYSTERY_LAYERS, generate_mystery_sequence
from json_utils import find_and_visualize_json_errors, join_lines_after_correct_json_errors

# Import UI tabs
from ui_tabs import create_story_graph_tab, create_3d_study_tab, create_resources_hub_tab, create_mechanic_translation_tab, create_llm_playtest_tab, create_big_rpg_scale_tab, create_dnd_gm_tab, create_story_architect_tab, create_narrative_engine_tab, create_config_analysis_tab
from ui_tabs.dnd_gm_tab import search_monsters, search_spells, search_magicitems, search_conditions, search_classes, get_monster_details, get_spell_details, get_magicitem_details

# ConfigConversionforExporttoPlatform moved to exporters/router.py
# find_and_visualize_json_errors, join_lines_after_correct_json_errors moved to json_utils.py

#---------------------------------------

def testgroupingUIremotely():
    with gr.Accordion("Mini-Tutorial & Resources", open=False) as testui:
        with gr.Tabs():
            # ============================================================
            # TAB 1: TUTORIAL
            # ============================================================
            with gr.Tab("Tutorial"):
                gr.HTML("""<div style="width: 100%; text-align: center; padding: 10px; background: #f0f0f0; border-radius: 8px;">
                    <b>Main Goal:</b> Rapid prototypes for education/training (game-based learning)<br>
                    <b>Secondary:</b> Plan stateful game mechanics with AI assistance<br>
                    <b>Workflow:</b> Config โ†’ Assets โ†’ Playtest โ†’ Port to Real Engine
                </div>""")

                # SECTION 1: Config Shape
                gr.Markdown("---")
                gr.Markdown("## 1. Config Shape - The Core Concept")
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### Video Explanation")
                        tutorial_video_1 = gr.Video(
                            value="testmedia/Hallo - My Current Understanding of a game is.mp4",
                            label="Config Shape Explained"
                        )
                        gr.HTML("<i>๐ŸŽฌ Talking head video placeholder - generate via Media Studio โ†’ Video Generation</i>")

                    with gr.Column(scale=1):
                        gr.Markdown("""### Config Structure

```json
{
  "masterlocation1": {
    "sublocation1": {
      "description": "What the player sees",
      "choices": ["option A", "option B"],
      "transitions": {
        "option A": "masterlocation1_sublocation2",
        "option B": "masterlocation2_start"
      },
      "consequences": {
        "option A": "lambda player: player.add_item('key')"
      },
      "media": ["background.png", "ambient.mp3"]
    }
  }
}
```

**Key Points:**
- **Masterlocations** = Major areas (village, forest)
- **Sublocations** = States within areas
- **Transitions** = Where choices lead
- **Consequences** = State changes
- **Media** = Images, audio, video, 3D
                        """)

                # SECTION 2: What This Space Can Do
                gr.Markdown("---")
                gr.Markdown("## 2. What This Space Can Do")
                with gr.Row():
                    with gr.Column(scale=1):
                        gr.Markdown("### Video Overview")
                        tutorial_video_2 = gr.Video(
                            value=None,
                            label="Capabilities Overview"
                        )
                        gr.HTML("<i>๐ŸŽฌ Talking head video placeholder - generate via Media Studio โ†’ Video Generation</i>")

                    with gr.Column(scale=1):
                        gr.Markdown("""### Capabilities

**Create Games From:**
- Your ideas โ†’ LLM generates JSON config
- Textbooks, songs, memes โ†’ Interactive games
- Existing designs โ†’ Import and modify

**Test & Improve:**
- Play in-browser with state tracking
- LLM automated playtesting
- Config validation & Mermaid diagrams

**Export To:**
- PlayCanvas, Godot 4.x, GameMaker
- Flutter, Unreal Engine 5
- 2D Map visualizations (SVG)

**Design Tools:**
- Mechanic Translation (1D โ†” 2D โ†” 3D)
- State system with logic gates
- D&D 5e SRD integration
                        """)

                # Generate Tutorial Videos Section
                gr.Markdown("---")
                with gr.Accordion("๐ŸŽฌ Generate Tutorial Videos", open=False):
                    gr.Markdown("""### How to Create Tutorial Videos

1. **Go to Media Studio โ†’ Video Generation**
2. **Upload a portrait image** (or generate one in Media Studio โ†’ HF Spaces โ†’ Images)
3. **Enter the script text** - the AI will generate TTS and animate the portrait

**Suggested Scripts:**

**Video 1 - Config Shape:**
> "The config is a nested JSON structure that defines your game. At the top level, you have masterlocations like village or forest. Inside each are sublocations - the actual game states. Each state has a description players see, choices they can make, transitions to other states, and media like images or audio."

**Video 2 - Capabilities:**
> "This space helps you prototype games quickly. Generate configs from your ideas using AI, test them right in your browser with live state tracking, then export to real game engines like Godot or Unreal. You can also generate images, audio, 3D models, and even talking head videos like this one."
                    """)

                with gr.Accordion("Legacy Video Tutorial", open=False):
                    gr.Markdown("Original prototype videos using Hallo")
                    gr.Video(value="testmedia/Hallo - My Current Understanding of a game is.mp4")
                    gr.HTML("Talking portrait spaces: <a href='https://huggingface.co/spaces/fffiloni/tts-hallo-talking-portrait'>Hallo TTS</a> | <a href='https://huggingface.co/spaces/vinthony/SadTalker'>SadTalker</a>")

            # ============================================================
            # TAB 2: IMPROVEMENT PROCESS
            # ============================================================
            with gr.Tab("Improvement Process"):
                gr.Markdown("""## The Improvement Process - Core Abstraction

The key insight: **systematic improvement with access to the original enables real analysis.**

This isn't about UI buttons - it's about understanding HOW configs get better.""")

                gr.Markdown("---")
                gr.Markdown("### The 4 Focus Areas")
                gr.Markdown("""
Each round of improvement focuses on ONE aspect. This prevents overwhelming changes and lets you see what each focus contributes.

| Round | Focus | What Changes | Feel Impact |
|-------|-------|--------------|-------------|
| **R1** | Environment | Descriptions gain sensory details, clues planted | World feels *real*, *explorable* |
| **R2** | Characters | NPCs gain motivations, dialogue reveals personality | World feels *inhabited*, *alive* |
| **R3** | Choices | More options per state, different approaches | Player feels *agency*, *freedom* |
| **R4** | Tension | Time pressure, red herrings, stakes raised | Player feels *urgency*, *engagement* |

**The order matters.** Environment first gives characters a world to inhabit. Characters give meaning to choices. Choices create opportunities for tension.
""")

                gr.Markdown("---")
                gr.Markdown("### Why Compare to Original?")
                gr.Markdown("""
Without the original, you can't answer:
- "Did this round actually improve things?"
- "What specifically changed?"
- "Did I lose something important?"

**The 5-round comparison view** (in Config Analysis) shows the same state across R0โ†’R4, so you can see the journey, not just the destination.
""")

                gr.Markdown("---")
                gr.Markdown("### Derivative Changes - The RPG Scale Challenge")
                gr.Markdown("""
At small scale (7-30 states), you can hold the whole config in your head.

At RPG scale (100+ states), changing one thing affects many others:

| You Change... | Consider Also Updating... |
|---------------|---------------------------|
| Location name | NPCs who mention it, quests there, travel descriptions |
| NPC role | Their dialogue, faction rank, what they sell |
| Faction relationship | Cross-faction dialogue, quest availability |
| Item properties | Recipes using it, quest objectives, merchant prices |

The **Derivative Analyzer** (in Big RPG Scale โ†’ Validation) shows these connections before you make changes.
""")

                gr.Markdown("---")
                gr.Markdown("### The Workflow Pattern")
                gr.Markdown("""
```
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  1. START                                               โ”‚
โ”‚     Load a config (starter, demo, or your own)          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                          โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  2. ANALYZE                                             โ”‚
โ”‚     Current state: metrics, issues, graph visualization โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                          โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  3. IMPROVE (one focus at a time)                       โ”‚
โ”‚     Environment โ†’ Characters โ†’ Choices โ†’ Tension        โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                          โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  4. COMPARE                                             โ”‚
โ”‚     Side-by-side with original - what changed?          โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                          โ†“
โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
โ”‚  5. TEST                                                โ”‚
โ”‚     Playtest (manual or AI personas)                    โ”‚
โ”‚     Did the changes work? Any new issues?               โ”‚
โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                          โ†“
              โ”Œโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”
              โ”‚  Happy with result?   โ”‚
              โ””โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”˜
                    โ†“           โ†“
                   NO          YES
                    โ†“           โ†“
            Back to step 3   EXPORT to game engine
```

**The loop is the process.** Each cycle makes the config better. You always have the original to compare against.
""")

                gr.Markdown("---")
                gr.Markdown("### Coming Full Circle")
                gr.Markdown("""
This space's purpose:
1. **Idea exposure** - See what's possible with game configs
2. **Abstract the improvement process** - Learn the pattern, not just the tools

Once you internalize the 4-focus improvement cycle, you can apply it anywhere - with or without this UI.
""")

                gr.Markdown("---")
                with gr.Accordion("๐ŸŽฌ Tutorial Video Scripts", open=False):
                    gr.Markdown("""### Generate These Videos in Media Studio โ†’ Talking Head

**How to use:** Copy a script below, go to Media Studio โ†’ Video Generation โ†’ Talking Head tab,
upload a portrait image, paste the script text, and generate.

---

**Video 1: The 4 Focus Areas** (~45 seconds)
```
When improving a game config, we focus on ONE aspect at a time.

Round one: Environment. Descriptions gain sensory details - what you see, hear, smell.
The world starts feeling real and explorable.

Round two: Characters. NPCs gain motivations and personality. Their dialogue reveals who they are.
The world feels inhabited.

Round three: Choices. More options per state. Different approaches to problems.
The player feels agency.

Round four: Tension. Time pressure, red herrings, raised stakes.
The player feels urgency.

The order matters. Environment gives characters a world. Characters give meaning to choices.
Choices create opportunities for tension.
```

---

**Video 2: Why Compare to Original** (~30 seconds)
```
Why do we keep the original config alongside our improvements?

Because without it, you can't answer basic questions:
Did this round actually make things better?
What specifically changed?
Did we accidentally lose something important?

The five-round comparison view shows the same state across all rounds.
You see the journey, not just the destination.
That's how you learn what each focus area contributes.
```

---

**Video 3: The Workflow Loop** (~40 seconds)
```
The improvement process is a loop, not a straight line.

Start with a config - a starter, a demo, or your own.
Analyze it. What's the current state? Any issues?
Improve it - one focus at a time.
Compare to the original. What changed?
Test it. Play through. Did the changes work?

If you're happy, export to your game engine.
If not, go back to improve. Each cycle makes the config better.

You always have the original to compare against.
That's the key insight: systematic improvement with access to the original enables real analysis.
```

---

**Tips:**
- Use a clear, front-facing portrait image
- Each video takes 1-5 minutes to generate depending on text length
- SadTalker works best with natural-sounding scripts
""")

            # ============================================================
            # TAB 3: RESOURCES (moved from Media Studio)
            # ============================================================
            with gr.Tab("Resources"):
                gr.Markdown("## Inspiration, Learning & Licensing")

                with gr.Accordion("Chat UIs - Free Tier LLMs", open=False):
                    gr.HTML("""<a href="https://huggingface.co/chat" target="_blank">Hugging Face Chat</a> | <a href="https://huggingface.co/spaces/akhaliq/anychat" target="_blank">AnyChat (Latest Releases)</a>""")
                    gr.HTML("You can turn any space into a tool for huggingchat and the default image tool can do 5-10 secs per image - paste the current description and ask for images")
                    gr.HTML("Huggingface chat supports - State Management (Threads), Image Generation and editing, Websearch, Document parsing (PDF?), Assistants and larger models than zero gpu can support in July 2024 (Unquantised 30B and above)")
                    gr.HTML("""<a href="https://lambda.chat/chatui/" target="_blank">Lambda Chat</a> - beta and text only - no login so chats expire (October 2024)""")
                    gr.HTML("ChatGPT is good for multiple images in one image - eg game maps and for this space all decisions in one picture")
                    gr.HTML("Gemini")
                    gr.HTML("Claude - Coding")
                    gr.HTML("Existing Assistants to use and planning custom assistants placeholder")

                with gr.Accordion("Idea / Inspiration Sources", open=False):
                    with gr.Row():
                        gr.HTML("""Licenses for the spaces still to be evaluated - June 2024 <br> Users to follow with cool spaces: <br>
                            <a href="https://huggingface.co/osanseviero" target="_blank">osanseviero</a> - <a href="https://huggingface.co/spaces/osanseviero/TheMLGame" target="_blank">TheMLGame</a><br>
                            <a href="https://huggingface.co/jbilcke-hf" target="_blank">jbilcke-hf</a><br>
                            <a href="https://huggingface.co/dylanebert" target="_blank">dylanebert</a><br>
                            <a href="https://huggingface.co/fffiloni" target="_blank">fffiloni</a><br>
                            <a href="https://huggingface.co/artificialguybr" target="_blank">artificialguybr</a><br>
                            <a href="https://huggingface.co/radames" target="_blank">radames</a><br>
                            <a href="https://huggingface.co/multimodalart" target="_blank">multimodalart</a>""")
                        gr.HTML("""Some Youtube Channels to keep up with updates:<br><br>
                            <a href="https://www.youtube.com/@lev-selector" target="_blank">@lev-selector</a><br>
                            <a href="https://www.youtube.com/@fahdmirza/videos" target="_blank">@fahdmirza</a>""")
                        gr.HTML("""Social media that shows possibilities:<br><br>
                            <a href="https://www.reddit.com/r/aivideo/" target="_blank">r/aivideo</a> |
                            <a href="https://www.reddit.com/r/StableDiffusion/" target="_blank">r/StableDiffusion</a> |
                            <a href="https://www.reddit.com/r/midjourney/" target="_blank">r/midjourney</a> |
                            <a href="https://x.com/blizaine" target="_blank">@blizaine</a> |
                            <a href="https://www.reddit.com/r/singularity/" target="_blank">r/singularity</a>""")

                with gr.Accordion("Examples of Generated Media on Reddit", open=False):
                    gr.HTML("""<a href="https://www.reddit.com/r/singularity/comments/1fknejj/facecamai_lets_anyone_convert_a_single_image_into/" target="_blank">FaceCam AI - convert image into video</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1fjylow/tripo_v20_is_out_now_you_can_create_stunning_3d/" target="_blank">Tripo v2.0 - stunning 3D</a>""")

                with gr.Accordion("Licensing Notes", open=False):
                    gr.HTML("""To be continued.... Need to find the press release to see license eg. <a href="https://blackforestlabs.ai/announcing-black-forest-labs/" target="_blank">Black Forest Labs announcement</a>""")

                with gr.Accordion("Future Developments / Links to Integrate", open=False):
                    gr.HTML("""<a href="https://www.reddit.com/r/singularity/comments/1fhbipv/some_video_games_made_entirely_by_o1preview_and/" target="_blank">Video games made entirely by o1-preview</a>""")
                    gr.HTML("""<a href="https://artificialanalysis.ai/" target="_blank">Artificial Analysis</a> | <a href="https://lmarena.ai" target="_blank">lmarena.ai</a> | <a href="https://web.lmarena.ai" target="_blank">web.lmarena.ai</a>""")
                    gr.HTML("""
                        <b>Apache 2.0 models to aim for:</b><br>
                        <a href="https://huggingface.co/models?pipeline_tag=text-to-image&license=license:apache-2.0&sort=trending" target="_blank">HF Text-to-Image (Apache 2.0)</a><br><br>

                        <b>Inspiration and food for thought:</b><br>
                        <a href="https://tost.ai/" target="_blank">tost.ai</a> |
                        <a href="https://huggingface.co/spaces/yslan/GaussianAnything-AIGC3D" target="_blank">GaussianAnything-AIGC3D</a> |
                        <a href="https://huggingface.co/models?pipeline_tag=image-to-3d&sort=trending" target="_blank">HF Image-to-3D</a><br>
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1h35a3w/list_of_every_mcp_server_that_i_could_find/" target="_blank">List of MCP Servers</a> - <a href="https://github.com/punkpeye/awesome-mcp-servers" target="_blank">awesome-mcp-servers</a><br>
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1h8sfyh/test_llama_mesh_blender_addon/" target="_blank">Llama Mesh Blender addon</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1h97guv/clone_robotics_torso_2_with_910_muscle_fibers_and/" target="_blank">Clone Robotics Torso 2</a><br>
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1h7g4ur/moondream_launches_05b_vision_language_model_open/" target="_blank">Moondream 0.5B VLM</a> |
                        <a href="https://github.com/BrokenSource/DepthFlow" target="_blank">DepthFlow</a><br>
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1g3djqv/playing_aigenerated_csgo_on_a_single_rtx_3090_in/" target="_blank">AI-generated CSGO on RTX 3090</a><br>
                        <a href="https://thuwzy.github.io/" target="_blank">thuwzy.github.io</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1g3m1fl/its_just_an_indian_man_teleoperating/" target="_blank">Teleoperating robots</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1g2gg8i/tesla_optimus_bot_interacting_with_a_crowd_these/" target="_blank">Tesla Optimus</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1g2ujf7/police_robots_in_china/" target="_blank">Police robots in China</a><br>
                        <a href="https://www.reddit.com/r/aivideo/" target="_blank">r/aivideo</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1g2vsu0/driver_2_ps1_gameplay_but_its_reimagined_by_ai_oh/" target="_blank">Driver 2 PS1 reimagined by AI</a><br>
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1fspsp9/experimenting_with_llama3_codebase_and_google/" target="_blank">Llama3 codebase experiments</a><br>
                        <a href="https://huggingface.co/collections/unsloth/llama-32-all-versions-66f46afde4ca573864321a22" target="_blank">Llama 3.2 all versions</a> - cpu application considerations<br>
                        <a href="https://huggingface.co/spaces/severo/hf-forum-dashboard" target="_blank">HF Forum Dashboard</a> - how can we make a dashboard for the game<br>
                        <a href="https://huggingface.co/spaces/alibaba-pai/CogVideoX-Fun-5b" target="_blank">CogVideoX-Fun-5b</a> - Video Gen<br>
                        <a href="https://huggingface.co/spaces/gabrielchua/open-notebooklm" target="_blank">open-notebooklm</a> |
                        <a href="https://huggingface.co/spaces/lamm-mit/PDF2Audio" target="_blank">PDF2Audio</a> |
                        <a href="https://huggingface.co/spaces/ThomasSimonini/Roblox-3D-Assets-Generator-v1" target="_blank">Roblox 3D Assets Generator</a><br>
                        <a href="https://huggingface.co/datasets?modality=modality:video&library=library:datasets&sort=trending" target="_blank">HF Video Datasets</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1h4478l/midjourney_kling_ai_15_motion_brush_is_amazing/" target="_blank">Midjourney Kling AI Motion Brush</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1g4wx27/dart_can_generate_highquality_human_motions_in/" target="_blank">DART human motions</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1h6n2ve/genie_2_the_new_ai_from_google_that_generates/" target="_blank">Genie 2 from Google</a> |
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1h730yb/samurai_vs_metas_sam_2_a_new_era_in_visual/" target="_blank">SAMURAI vs SAM 2</a><br>
                        <a href="https://huggingface.co/spaces/JeffreyXiang/TRELLIS" target="_blank">TRELLIS</a> |
                        <a href="https://huggingface.co/apple/DepthPro" target="_blank">Apple DepthPro</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1hdk0do/pika_20_is_here_even_for_europeans/" target="_blank">Pika 2.0</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1hejhqb/okaywhatever_pikalabs_has_done_with_their/" target="_blank">Pika Labs update</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1hgkkyn/new_paper_presents_exbody2_a_wholebody_tracking/" target="_blank">ExBody2 whole-body tracking</a> |
                        <a href="https://ai.meta.com/blog/meta-fair-updates-agents-robustness-safety-architecture/" target="_blank">Meta FAIR updates</a><br>
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1hzfjmp/parking_systems_analysis_and_report_generation/" target="_blank">Parking systems analysis</a> |
                        <a href="https://www.reddit.com/r/aivideo/comments/1i1hz83/joust_official_trailer/" target="_blank">Joust trailer</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1hz5wz1/tutorial_run_moondream_2bs_new_gaze_detection_on/" target="_blank">Moondream 2B gaze detection</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1hsaox8/day_two_of_2025_and_we_already_got_text_to_cad/" target="_blank">Text to CAD</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1hsp94z/replicated_this_gorgeous_technique_with_ai_what/" target="_blank">Gorgeous AI technique</a> |
                        <a href="https://www.reddit.com/r/ClaudeAI/comments/1hs7yi9/imagine_youre_an_ai_giving_a_standup_set_to_a/" target="_blank">AI standup comedy</a><br>
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1hrrvt8/awesome_blog_post_on_llama_mesh/" target="_blank">Llama Mesh blog post</a> |
                        <a href="https://huggingface.co/spaces/dylanebert/research-tracker" target="_blank">Research Tracker</a><br>
                        <a href="https://huggingface.co/spaces/HuggingFaceH4/blogpost-scaling-test-time-compute" target="_blank">Scaling Test-Time Compute</a> |
                        <a href="https://huggingface.co/spaces/shachar/chess-openings" target="_blank">Chess Openings</a> |
                        <a href="https://huggingface.co/spaces/akhaliq/anychat" target="_blank">AnyChat</a><br><br>

                        <b>MIT filter + Modality:</b><br>
                        <a href="https://huggingface.co/datasets?modality=modality:audio&license=license:mit&sort=trending" target="_blank">HF Audio Datasets (MIT)</a> |
                        <a href="https://huggingface.co/datasets?modality=modality:video&license=license:mit&sort=trending" target="_blank">HF Video Datasets (MIT)</a><br>
                        <a href="https://huggingface.co/datasets/lmms-lab/VideoChatGPT" target="_blank">VideoChatGPT Dataset</a> - GPU poverty workaround<br>
                        <a href="https://huggingface.co/lianghsun/Llama-3.2-Taiwan-Legal-3B-Instruct-LoRA" target="_blank">Llama 3.2 Taiwan Legal LoRA</a> - How LoRAs work<br>
                        <a href="https://huggingface.co/RED-AIGC/StoryMaker" target="_blank">StoryMaker</a> - Consistency |
                        <a href="https://huggingface.co/fishaudio/fish-speech-1.4" target="_blank">Fish Speech 1.4</a> |
                        <a href="https://huggingface.co/spaces/gpt-omni/mini-omni" target="_blank">mini-omni</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1fp0ti3/alibaba_presents_mimo_controllable_character/" target="_blank">Alibaba MiMo controllable character</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1fq78tq/chatgpt_powered_by_jamaican_vibes/" target="_blank">ChatGPT Jamaican vibes</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1ftmi99/openai_has_released_whisper_v3_turbo_model/" target="_blank">Whisper v3 Turbo</a> |
                        <a href="https://huggingface.co/spaces/jadechoghari/OpenMusic" target="_blank">OpenMusic</a> |
                        <a href="https://huggingface.co/spaces/AIDC-AI/Ovis1.6-Gemma2-9B" target="_blank">Ovis1.6-Gemma2-9B</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1fuel03/harvard_students_build_and_show_off_ar_glasses/" target="_blank">Harvard AR glasses</a> |
                        <a href="https://huggingface.co/datasets/KingNish/reasoning-base-20k" target="_blank">reasoning-base-20k</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1fxdvyz/nvidia_presents_edgerunner_the_method_can/" target="_blank">NVIDIA EdgeRunner</a> |
                        <a href="https://buaacyw.github.io/mesh-anything/" target="_blank">MeshAnything</a><br>
                        <a href="https://www.reddit.com/r/3Dprinting/" target="_blank">r/3Dprinting</a> |
                        <a href="https://www.reddit.com/r/3Dprinting/comments/1fxb5pc/color_lithopanes/" target="_blank">Color lithopanes</a><br>
                        <a href="https://huggingface.co/facebook/sam2.1-hiera-base-plus" target="_blank">SAM 2.1 Hiera Base Plus</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1fyax9h/monst3r_a_simple_approach_for_estimating_geometry/" target="_blank">MONST3R geometry estimation</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1g2kuu3/visionbased_hand_gesture_customization_from_apple/" target="_blank">Apple hand gesture</a><br>
                        <a href="https://huggingface.co/spaces/Zyphra/Zamba2-7B" target="_blank">Zamba2-7B</a> |
                        <a href="https://huggingface.co/papers/2410.10306" target="_blank">Paper 2410.10306</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1hkoo08/unitree_has_a_new_offroad_video/" target="_blank">Unitree offroad</a> |
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1i26nk4/attention_is_all_you_need_pt_2_titans_learning_to/" target="_blank">Titans learning</a><br>
                        <a href="https://huggingface.co/blog/eliebak/minimax01-deepdive" target="_blank">MiniMax01 deepdive</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1hu5lf7/killed_by_llm/" target="_blank">Killed by LLM</a><br>
                        <a href="https://polymathic-ai.org/the_well/datasets_overview/" target="_blank">Polymathic AI datasets</a> |
                        <a href="https://epoch.ai/frontiermath" target="_blank">FrontierMath</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1husayt/robotic_firearm_openal_realtime_api_integration/" target="_blank">Robotic firearm OpenAI integration</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1i1qyx1/why_grokking_emergent_understanding_happens_in/" target="_blank">Why grokking happens</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1iklreg/what_fictional_characters_are_going_to_get/" target="_blank">Fictional characters</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1ioccgr/introducing_%F0%9D%90%83%F0%9D%90%B2%F0%9D%90%A7%F0%9D%90%9A%F0%9D%90%A6%F0%9D%90%A2%F0%9D%90%9C%F0%9D%90%82%F0%9D%90%A2%F0%9D%90%AD%F0%9D%90%B2_a_new_generation/" target="_blank">DynamicCity</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1inuyws/meta_unveils_ai_models_that_convert_brain/" target="_blank">Meta brain-to-AI models</a><br>
                        <a href="https://cgdream.ai/pricing" target="_blank">CGDream pricing</a> |
                        <a href="https://tensor.art/" target="_blank">Tensor.art</a><br>
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1icyei9/openr1_from_huggingface/" target="_blank">OpenR1 from HuggingFace</a> |
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1iohk4o/lets_build_deepseek_from_scratch_taught_by_mit/" target="_blank">Build DeepSeek from scratch (MIT)</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1iy8s9h/claude_37_is_playing_pok%C3%A9mon_red_on_twitch/" target="_blank">Claude 3.7 plays Pokemon</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1ixw0pc/omg_claude_sonnet_37_is_insane_i_got_this/" target="_blank">Claude Sonnet 3.7 is insane</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1ixi1r8/claude_37_sonnet_can_generate_manim_code_heres_a/" target="_blank">Claude 3.7 Manim code</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1ixajw5/holy_sht_they_cooked_claude_37_coded_this_game/" target="_blank">Claude 3.7 coded game</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1ixad2g/flappy_bird_oneshot_claude_37_vs_o3_minihigh/" target="_blank">Flappy Bird Claude 3.7 vs o3-mini</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1iw89mr/google_veo_2_pricing_is_at_050_per_second/" target="_blank">Google Veo 2 pricing</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1ixfztn/fish_tank_boids_simulation_oneshot_claude_37/" target="_blank">Boids simulation Claude 3.7</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1ixf08q/combining_ai_with_real_footage/" target="_blank">AI + real footage</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1ixcbfo/3d_unicorn_by_claude_37_single_blender_python/" target="_blank">3D Unicorn Claude 3.7 Blender</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1iwcvu8/veo_2_is_insane_with_videogames_nearly_perfect/" target="_blank">Veo 2 videogames</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1iwajhd/more_google_veo_videos_more_in_comment/" target="_blank">More Google Veo videos</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1ivoaz7/cast_recovering_highquality_3d_scenes_from_a/" target="_blank">CAST 3D scene recovery</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1iymrxs/shanghai_robot_factory_where_humanoid_robots_are/" target="_blank">Shanghai robot factory</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1izbqyn/claude_has_been_trapped_on_mt_moon_for_16_hours/" target="_blank">Claude trapped in Mt Moon</a><br>
                        <a href="https://www.reddit.com/r/godot/comments/lhtabd/i_made_an_easy_to_use_docker_image_for_godot/" target="_blank">Godot Docker image</a> |
                        <a href="https://huggingface.co/spaces?category=game-ai" target="_blank">HF Game-AI Spaces</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1izmd45/building_a_robot_that_can_see_hear_talk_and_dance/" target="_blank">Robot that can see, hear, talk, dance</a> |
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1izfy2d/llada_large_language_diffusion_model_weights_demo/" target="_blank">LLaDA diffusion model</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1ixt9ut/google_deepmind_launches_free_gemini_code_assist/" target="_blank">Gemini Code Assist free</a><br>
                        <a href="https://kimi.ai/" target="_blank">Kimi.ai</a> |
                        <a href="https://chat.inceptionlabs.ai/" target="_blank">Inception Labs Chat</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1ja0j50/vace_allinone_video_creation_and_editing/" target="_blank">VACE all-in-one video</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1j9nro2/now_gemini_can_create_visual_stories_with_native/" target="_blank">Gemini visual stories</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1jai85n/oneshot_character_consistency_has_been_solved_by/" target="_blank">One-shot character consistency solved</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1jnzsh9/found_this_guy_turned_his_phone_video_into_a/" target="_blank">Phone video to animation</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1joaowb/claude_working_inside_of_blender/" target="_blank">Claude inside Blender</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1jnxtiy/anybody_using_the_new_model_to_make_animations/" target="_blank">New model for animations</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1jkzjjn/forcing_gpt_4o_native_image_gen_to_generate_a/" target="_blank">Forcing GPT-4o image gen</a><br>
                        <a href="https://www.google.com/search?q=mathoverflow" target="_blank">MathOverflow (Google)</a> |
                        <a href="https://mathoverflow.net/" target="_blank">MathOverflow</a><br>
                        <a href="https://weblog.jamisbuck.org/2011/1/3/maze-generation-kruskal-s-algorithm" target="_blank">Maze generation Kruskal's algorithm</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1jx8bj2/amputee_with_new_prosthetics_presumedly/" target="_blank">Amputee with new prosthetics</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1jwmnyj/people_are_sleeping_on_the_improved_chatgpt_memory/" target="_blank">ChatGPT memory improved</a><br>
                        <a href="https://research.google/blog/accelerating-scientific-breakthroughs-with-an-ai-co-scientist/" target="_blank">Google AI Co-Scientist</a><br>
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1jjsiiw/mario_game_made_by_new_a_gemini_pro_25_in_couple/" target="_blank">Mario game by Gemini Pro 2.5</a> |
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1jevseg/new_multiview_3d_model_by_stability_ai/" target="_blank">Multiview 3D by Stability AI</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1jeqys9/meta_releases_new_lightningfast_3d_model/" target="_blank">Meta lightning-fast 3D</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1k1ilmj/feeling_the_agi_strong_today_what_a_timeline/" target="_blank">Feeling the AGI strong</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1jy01p5/optimusalphas_mcbench_builds_this_thing_has_the/" target="_blank">OptimusAlpha MCBench builds</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1kemzuo/berkeley_humanoid_lite_an_open_source_5k_and/" target="_blank">Berkeley Humanoid Lite $5k</a><br>
                        <a href="https://www.reddit.com/r/singularity/comments/1kf6thb/i_challenged_myself_to_make_a_2minute_short_film/" target="_blank">2-minute AI short film</a> |
                        <a href="https://www.reddit.com/r/singularity/comments/1kf6xbw/bytedance_dropped_uitars15_on_hugging_face_an/" target="_blank">ByteDance UI-TARS-1.5</a><br>
                        <a href="https://www.reddit.com/r/LocalLLaMA/comments/1ksklse/i_saw_a_project_that_im_interested_in_3dtown/" target="_blank">3DTown project</a><br><br>

                        <b>HF Games - Spaces:</b><br>
                        <a href="https://huggingface.co/spaces/dylanebert/FarmingGame/tree/main" target="_blank">FarmingGame</a> |
                        <a href="https://huggingface.co/spaces/godot-demo/godot-3d-trucks/tree/main" target="_blank">Godot 3D Trucks</a> |
                        <a href="https://huggingface.co/spaces/godot-demo/godot-2d/tree/main" target="_blank">Godot 2D</a><br>
                        <a href="https://huggingface.co/spaces/Mi6paulino/Tetris_Game/blob/main/index.html" target="_blank">Tetris Game</a> |
                        <a href="https://huggingface.co/spaces/DataScienceEngineering/1-SimPhysics-HTML5" target="_blank">SimPhysics-HTML5</a>
                    """)

                with gr.Accordion("Current Offline Ideas/Developments", open=False):
                    gr.HTML("""<a href="https://huggingface.co/blog/1_58_llm_extreme_quantization" target="_blank">1.58-bit LLM Extreme Quantization</a>""")

            # Resources Hub moved inside Mini-Tutorial & Resources
            create_resources_hub_tab()

    return testui

#-----------------------------------------------------------------------------------------------------------------------------------

with gr.Blocks() as demo:
    gr.HTML("<b>WIP</b> - Create Config / Improve existing config / Create Media / Plan Story Direction / Learn Some of the current tools available / Playtest")
    gr.HTML("This space (Q1 2024) original objective is obsolete as new 2025+ LLMs can make the UI reliably (and also struggle less with the syntax) so now is an <b>idea exposure tool</b> and to <b>abstract the improvement process</b> (which naturally means full workflow as well)")

    # ========== SHARED STATE FOR CROSS-TAB COMMUNICATION ==========
    # Stores paths of generated media (images, audio, video) for use in game config
    generated_media_paths = gr.State(value=[])
    # Stores the edited config from the render UI (for syncing back to config textbox)
    edited_config_state = gr.State(value="")

    testgroupingUIremotely()
    ui_gr_media_management_acc(generated_media_paths=generated_media_paths)

    with gr.Tab("Test"):
        with gr.Tab("Playtest & Edit"):
            gr.Markdown("## Playtest & Edit Workflow")
            gr.Markdown("Play the game on the left, edit config on the right. Changes sync back to config for reload.")

            # Load Demo Configs - prominently placed at top
            with gr.Accordion("Load a Demo Config", open=False):
                with gr.Tabs():
                    with gr.Tab("Traditional (No State)"):
                        gr.Markdown("*Classic configs with deterministic transitions and lambda consequences*")
                        with gr.Row():
                            ewpwa_demo_btn_village = gr.Button("Village Adventure (Basic)")
                            ewpwa_demo_btn_racing = gr.Button("Racing Game")
                            ewpwa_demo_btn_event = gr.Button("Event Planning")
                        with gr.Row():
                            ewpwa_demo_btn_timeline = gr.Button("Timeline Structure")
                            ewpwa_demo_btn_memory = gr.Button("Memory Fragments (Advanced)")
                    with gr.Tab("Stateful (With Logic Gates)"):
                        gr.Markdown("*Configs using conditions, effects, dynamic transitions, and state tracking*")
                        with gr.Row():
                            ewpwa_demo_btn_logic = gr.Button("Logic Gates Demo (Tavern)")
                            ewpwa_demo_btn_reference = gr.Button("State System Reference (Comprehensive)")

            # ============================================================
            # ONE-CLICK TO GAMEPLAY - Multiple Scenario Types
            # ============================================================
            with gr.Accordion("One-Click to Gameplay", open=False):
                gr.Markdown("### Generate Complete Game from Scenarios")
                gr.Markdown("Choose a scenario type, configure settings, generate assets, and auto-load into playtest.")

                # Shared generation settings (at top, used by all tabs)
                with gr.Accordion("Shared Generation Settings", open=False):
                    otg_gen_mode = gr.Radio(
                        ["Local (ZeroGPU)", "API"],
                        value="Local (ZeroGPU)",
                        label="Generation Mode"
                    )
                    with gr.Row():
                        otg_text_model = gr.Dropdown(
                            choices=modelnames,
                            value=modelnames[1] if len(modelnames) > 1 else modelnames[0],
                            label="Text Model"
                        )
                        otg_image_model = gr.Dropdown(
                            choices=imagemodelnames,
                            value=imagemodelnames[0],
                            label="Image Model"
                        )
                    with gr.Row():
                        otg_media_type = gr.Dropdown(
                            choices=["image", "audio", "3d", "tts"],
                            value="image",
                            label="Media Type",
                            scale=1
                        )

                # Tabs for different scenario types
                with gr.Tabs():
                    # ==================== TAB 1: FILM SCENARIOS (Original Videographer) ====================
                    with gr.Tab("Film Scenarios"):
                        gr.Markdown("**Videographer's perspective** - Generate from film scene types")

                        with gr.Row():
                            otg_count = gr.Slider(minimum=3, maximum=10, value=5, step=1, label="Number of Scenes")

                        with gr.Row():
                            otg_opening = gr.Checkbox(label="Openings", value=True)
                            otg_tension = gr.Checkbox(label="Tension", value=True)
                            otg_action = gr.Checkbox(label="Action", value=True)
                            otg_emotional = gr.Checkbox(label="Emotional", value=True)

                        with gr.Row():
                            otg_discovery = gr.Checkbox(label="Discovery", value=True)
                            otg_social = gr.Checkbox(label="Social", value=True)
                            otg_ending = gr.Checkbox(label="Endings", value=True)

                        with gr.Row():
                            otg_force_opening = gr.Checkbox(label="Force Opening First", value=True)
                            otg_force_ending = gr.Checkbox(label="Force Ending Last", value=True)

                        with gr.Row():
                            otg_generate_btn = gr.Button("Generate Film Scenario", variant="primary", scale=3)
                            otg_stop_btn = gr.Button("Stop", variant="stop", scale=1, visible=False)

                    # ==================== TAB 2: STORY BEATS (Writer's Perspective) ====================
                    with gr.Tab("Story Beats"):
                        gr.Markdown("**Writer's perspective** - Generate from narrative beat structures")

                        with gr.Row():
                            otg_beat_format = gr.Dropdown(
                                choices=[
                                    ("90-Minute Feature Film", "film_90min"),
                                    ("30-Minute TV Episode", "tv_30min"),
                                    ("9-Minute YouTube Video", "youtube_9min"),
                                    ("3-Minute Short", "short_3min"),
                                ],
                                value="film_90min",
                                label="Format"
                            )
                            otg_beat_genre = gr.Dropdown(
                                choices=[
                                    ("Action", "action"),
                                    ("Drama", "drama"),
                                    ("Comedy", "comedy"),
                                    ("Thriller", "thriller"),
                                    ("Romance", "romance"),
                                    ("Sci-Fi", "scifi"),
                                    ("Fantasy", "fantasy"),
                                    ("Horror", "horror"),
                                ],
                                value="thriller",
                                label="Genre"
                            )

                        with gr.Row():
                            otg_beat_count = gr.Slider(minimum=3, maximum=15, value=6, step=1, label="Number of Beats")

                        with gr.Row():
                            otg_beat_generate_btn = gr.Button("Generate Story Beats", variant="primary", scale=3)

                    # ==================== TAB 3: D&D ADVENTURE ====================
                    with gr.Tab("D&D Adventure"):
                        gr.Markdown("**Fantasy RPG** - Generate from D&D encounter types")

                        with gr.Row():
                            otg_dnd_difficulty = gr.Dropdown(
                                choices=[
                                    ("Easy", "easy"),
                                    ("Medium", "medium"),
                                    ("Hard", "hard"),
                                    ("Deadly", "deadly"),
                                ],
                                value="medium",
                                label="Difficulty"
                            )
                            otg_dnd_count = gr.Slider(minimum=3, maximum=10, value=5, step=1, label="Encounter Count")

                        with gr.Row():
                            otg_dnd_combat = gr.Checkbox(label="Combat", value=True)
                            otg_dnd_social = gr.Checkbox(label="Social", value=True)
                            otg_dnd_exploration = gr.Checkbox(label="Exploration", value=True)
                            otg_dnd_puzzle = gr.Checkbox(label="Puzzle", value=True)

                        with gr.Row():
                            otg_dnd_boss = gr.Checkbox(label="Include Boss Fight", value=True)
                            otg_dnd_force_boss_end = gr.Checkbox(label="Boss at End", value=True)

                        with gr.Row():
                            otg_dnd_generate_btn = gr.Button("Generate D&D Adventure", variant="primary", scale=3)

                    # ==================== TAB 4: WORLD EXPLORER ====================
                    with gr.Tab("World Explorer"):
                        gr.Markdown("**Geography perspective** - Generate explorable world locations")

                        with gr.Row():
                            otg_world_count = gr.Slider(minimum=3, maximum=12, value=6, step=1, label="Number of Locations")

                        with gr.Row():
                            otg_world_forest = gr.Checkbox(label="Forest", value=True)
                            otg_world_mountain = gr.Checkbox(label="Mountain", value=True)
                            otg_world_desert = gr.Checkbox(label="Desert", value=False)
                            otg_world_coastal = gr.Checkbox(label="Coastal", value=True)

                        with gr.Row():
                            otg_world_urban = gr.Checkbox(label="Urban", value=True)
                            otg_world_swamp = gr.Checkbox(label="Swamp", value=False)
                            otg_world_tundra = gr.Checkbox(label="Tundra", value=False)
                            otg_world_urban_start = gr.Checkbox(label="Start in City", value=True)

                        with gr.Row():
                            otg_world_generate_btn = gr.Button("Generate World Map", variant="primary", scale=3)

                    # ==================== TAB 5: TIMELINE ====================
                    with gr.Tab("Timeline"):
                        gr.Markdown("**Chronological perspective** - Generate time-based narrative")

                        with gr.Row():
                            otg_timeline_count = gr.Slider(minimum=3, maximum=12, value=6, step=1, label="Number of Events")

                        with gr.Row():
                            otg_timeline_morning = gr.Checkbox(label="Morning", value=True)
                            otg_timeline_midday = gr.Checkbox(label="Midday", value=True)
                            otg_timeline_afternoon = gr.Checkbox(label="Afternoon", value=True)
                            otg_timeline_evening = gr.Checkbox(label="Evening", value=True)

                        with gr.Row():
                            otg_timeline_night = gr.Checkbox(label="Night", value=True)
                            otg_timeline_past = gr.Checkbox(label="Flashbacks", value=False)
                            otg_timeline_future = gr.Checkbox(label="Flash-forwards", value=False)
                            otg_timeline_chrono = gr.Checkbox(label="Chronological Order", value=True)

                        with gr.Row():
                            otg_timeline_generate_btn = gr.Button("Generate Timeline", variant="primary", scale=3)

                    # ==================== TAB 6: EMOTIONAL JOURNEY ====================
                    with gr.Tab("Emotional Journey"):
                        gr.Markdown("**Song/Lyrics perspective** - Generate emotional arc narrative")

                        with gr.Row():
                            otg_song_count = gr.Slider(minimum=3, maximum=10, value=6, step=1, label="Number of Emotional Beats")
                            otg_song_arc = gr.Dropdown(
                                choices=[
                                    ("Varied Journey", "journey"),
                                    ("Building Crescendo", "crescendo"),
                                    ("Tension to Peace", "resolution"),
                                ],
                                value="journey",
                                label="Emotional Arc"
                            )

                        with gr.Row():
                            otg_song_joy = gr.Checkbox(label="Joy", value=True)
                            otg_song_sorrow = gr.Checkbox(label="Sorrow", value=True)
                            otg_song_anger = gr.Checkbox(label="Anger", value=False)
                            otg_song_fear = gr.Checkbox(label="Fear", value=False)

                        with gr.Row():
                            otg_song_hope = gr.Checkbox(label="Hope", value=True)
                            otg_song_nostalgia = gr.Checkbox(label="Nostalgia", value=True)
                            otg_song_peace = gr.Checkbox(label="Peace", value=True)

                        with gr.Row():
                            otg_song_generate_btn = gr.Button("Generate Emotional Journey", variant="primary", scale=3)

                    # ==================== TAB 7: MYSTERY ====================
                    with gr.Tab("Mystery"):
                        gr.Markdown("**Investigation perspective** - Generate layered mystery (iceberg model)")

                        with gr.Row():
                            otg_mystery_count = gr.Slider(minimum=3, maximum=10, value=5, step=1, label="Number of Clues/Reveals")

                        with gr.Row():
                            otg_mystery_surface = gr.Checkbox(label="Surface Clues", value=True)
                            otg_mystery_shallow = gr.Checkbox(label="Shallow Secrets", value=True)
                            otg_mystery_mid = gr.Checkbox(label="Mid-Depth", value=True)

                        with gr.Row():
                            otg_mystery_deep = gr.Checkbox(label="Deep Truths", value=True)
                            otg_mystery_abyss = gr.Checkbox(label="Core Truth (Abyss)", value=True)
                            otg_mystery_gradual = gr.Checkbox(label="Gradual Reveal", value=True)

                        with gr.Row():
                            otg_mystery_generate_btn = gr.Button("Generate Mystery", variant="primary", scale=3)

                # Progress display
                otg_progress_md = gr.Markdown("**Status:** Ready - Configure settings and click Generate")
                otg_current_item = gr.Textbox(label="Current Item", interactive=False, visible=False)

                # Preview outputs (collapsed by default)
                with gr.Accordion("Generation Preview", open=False):
                    otg_sequence_preview = gr.Markdown(label="Generated Sequence")
                    otg_config_preview = gr.Code(label="Generated Config", language="json", lines=10)
                    otg_queue_display = gr.Dataframe(
                        headers=["#", "Type", "Prompt", "Status"],
                        label="Queue Status",
                        interactive=False
                    )

                # AI Assistance Prompt section
                with gr.Accordion("AI Assistance Prompt (Copy to Chat)", open=False):
                    gr.Markdown("Generate a prompt to paste into ChatGPT/Claude for expanding and improving your config.")
                    with gr.Row():
                        otg_prompt_type = gr.Dropdown(
                            choices=[
                                ("Auto-detect from config", "auto"),
                                ("World/Geography Exploration", "world"),
                                ("Timeline/Chronological Story", "timeline"),
                                ("Emotional Journey/Song", "song"),
                                ("Mystery/Investigation", "mystery"),
                                ("D&D/Fantasy Adventure", "dnd"),
                                ("Film/Video Scenes", "film"),
                                ("Story Beats", "beats")
                            ],
                            value="auto",
                            label="Config Type",
                            scale=2
                        )
                        otg_prompt_focus = gr.Dropdown(
                            choices=[
                                ("Balanced improvements", "balanced"),
                                ("Add more detail/descriptions", "detail"),
                                ("Add more choices/branches", "choices"),
                                ("Deepen character motivations", "characters"),
                                ("Add environmental storytelling", "environment"),
                                ("Increase dramatic tension", "tension")
                            ],
                            value="balanced",
                            label="Focus Area",
                            scale=2
                        )
                        otg_generate_prompt_btn = gr.Button("Generate AI Prompt", variant="secondary", scale=1)
                    otg_ai_prompt_output = gr.Code(
                        label="AI Prompt (click copy button to copy to your chat)",
                        language=None,
                        lines=12
                    )

                # Export section
                with gr.Accordion("Export Config + Media Files", open=False):
                    gr.Markdown("Download a ZIP containing the config JSON and all generated media files.")
                    with gr.Row():
                        otg_export_btn = gr.Button("Export as ZIP", variant="secondary")
                        otg_export_file = gr.File(label="Download ZIP", interactive=False)
                    otg_export_status = gr.Textbox(label="Export Status", interactive=False, lines=3)

                # Hidden state variables
                otg_generated_config = gr.State(value="")
                otg_prompts_text = gr.State(value="")

            with gr.Row():
                # ========== LEFT COLUMN: GAME PLAYTEST ==========
                with gr.Column(scale=1):
                    with gr.Group():
                        gr.Markdown("### Game Preview")

                        # Current state display
                        ewpwa_current_state_display = gr.Textbox(
                            label="Current State ID",
                            value="No game loaded",
                            interactive=False,
                            max_lines=1
                        )

                        # Use lazy getter to avoid import-time game initialization
                        _init_info = get_initgameinfo()
                        ewpwadescription = gr.Textbox(label="Current Situation", lines=3, value=_init_info[0])
                        ewpwamediabool = gr.State(value=True)
                        ewpwamedia = gr.State(["testmedia/Stable Audio - Raindrops, output.wav"])

                        @gr.render(inputs=ewpwamedia)
                        def dynamic_with_media(media_items):
                            if media_items and len(media_items) > 0:
                                for item in media_items:
                                    create_media_component(item)
                            else:
                                gr.Markdown("*No media for this scene*")

                        ewpwachoices = gr.Radio(label="Your Choices", choices=_init_info[1])
                        ewpwasubmit_btn = gr.Button("Make Choice", variant="primary")
                        ewpwagame_log = gr.Textbox(label="Game Log", lines=10, value=_init_info[2])
                        ewpwagame_session = gr.State(value=_init_info[3])

                    # Jump to State & Hot Reload controls
                    with gr.Accordion("Quick Navigation", open=False):
                        gr.Markdown("**Jump to any state** for testing, or **hot reload** after edits")
                        ewpwa_state_dropdown = gr.Dropdown(
                            label="Jump to State",
                            choices=[],
                            interactive=True
                        )
                        with gr.Row():
                            ewpwa_jump_btn = gr.Button("Jump to State")
                            ewpwa_hot_reload_btn = gr.Button("Hot Reload Config", variant="secondary")
                        ewpwa_export_log_btn = gr.Button("Export Playthrough Log")
                        ewpwa_exported_log = gr.Textbox(label="Exported Log", lines=5, visible=False)

                    with gr.Accordion("Config & Debug", open=False):
                        ewpwaerror_box = gr.Textbox(label="Path Errors", lines=2, value=get_path_errors())
                        gr.Markdown("**Quick Load Demo:**")
                        with gr.Row():
                            ewpwa_load_sandwich_btn = gr.Button("Sandwich Shop", variant="secondary", size="sm")
                            ewpwa_load_skyrim_btn = gr.Button("Skyrim RPG", variant="secondary", size="sm")
                            ewpwa_load_big_rpg_btn = gr.Button("Big RPG Scale", variant="secondary", size="sm")
                        ewpwacustom_config = gr.Textbox(label="Game Config (JSON)", lines=6)
                        with gr.Row():
                            ewpwacustom_configbtn = gr.Button("Load Config", variant="primary")
                            ewpwasync_from_edit_btn = gr.Button("Re-apply Last Edit")

                    # NEW: Template-based generation
                    with gr.Accordion("Generate from Template", open=False):
                        gr.Markdown("**Generate a config** from narrative templates or a text prompt")
                        ewpwa_template_dropdown = gr.Dropdown(
                            label="Narrative Template",
                            choices=[(v["name"], k) for k, v in NARRATIVE_TEMPLATES.items()],
                            value="heros_journey"
                        )
                        ewpwa_template_desc = gr.Textbox(
                            label="Template Description",
                            value=NARRATIVE_TEMPLATES["heros_journey"]["description"],
                            interactive=False,
                            lines=2
                        )
                        with gr.Row():
                            ewpwa_theme_dropdown = gr.Dropdown(
                                label="Theme",
                                choices=["fantasy", "scifi", "modern", "horror"],
                                value="fantasy"
                            )
                            ewpwa_endings_slider = gr.Slider(1, 5, value=3, step=1, label="Number of Endings")
                        ewpwa_generate_template_btn = gr.Button("Generate from Template", variant="primary")

                        gr.Markdown("---")
                        gr.Markdown("**Or generate from a text prompt:**")
                        ewpwa_prompt_input = gr.Textbox(
                            label="Describe your game",
                            placeholder="e.g., A mystery game with 4 endings where the player investigates a haunted mansion...",
                            lines=2
                        )
                        ewpwa_structure_dropdown = gr.Dropdown(
                            label="Structure Type",
                            choices=[("Linear", "linear"), ("Branching", "branching"), ("Hub & Spoke", "hub")],
                            value="branching"
                        )
                        ewpwa_generate_prompt_btn = gr.Button("Generate from Prompt")

                    with gr.Accordion("Generate Random (Legacy)", open=False):
                        with gr.Row():
                            ewptimeline_output_with_assets = gr.Textbox(label="Timeline", lines=8)
                            ewpstory_output = gr.Textbox(label="Story", lines=8)
                        with gr.Row():
                            ewptimeline_output_text = gr.Textbox(label="Suggestions", lines=4)
                            ewptimeline_selected_lists_text = gr.Textbox(label="Source Lists", lines=2)
                        with gr.Row():
                            ewpgenerate_no_story_timeline_points = gr.Slider(1, 30, value=10, step=1, label="Story Points")
                            ewpgenerate_no_ui_timeline_points = gr.Slider(1, 30, value=10, step=1, label="UI Points")
                        with gr.Row():
                            ewptimeline_num_lists_slider = gr.Slider(1, len(all_idea_lists), value=3, step=1, label="Idea Lists")
                            ewptimeline_items_per_list_slider = gr.Slider(1, 10, value=3, step=1, label="Items/List")
                        with gr.Row():
                            ewptimeline_include_existing_games = gr.Checkbox(label="Include Game Inspirations", value=True)
                            ewptimeline_include_multiplayer = gr.Checkbox(label="Include Multiplayer", value=True)
                        ewpgenerate_button = gr.Button("Generate Story and Timeline")

                # ========== RIGHT COLUMN: CONFIG EDITOR ==========
                with gr.Column(scale=1):
                    gr.Markdown("### Edit Config While Playing")

                    # State to hold edited config for syncing
                    ewpwa_edited_config = gr.State(value="")

                    # Display available media from saved_media folder (uploads + generations)
                    with gr.Accordion("Available Media Files (uploads + generated)", open=False):
                        ewpwa_media_paths_display = gr.Textbox(
                            label="All media files in saved_media/ - copy filenames into media fields below",
                            lines=5,
                            interactive=False
                        )
                        ewpwa_refresh_media_btn = gr.Button("Refresh Media List")

                        def get_media_paths_display(gen_paths):
                            # Get all files from saved_media folder
                            all_files = get_all_media_files()
                            if all_files:
                                return "\n".join(all_files)
                            return "No media files yet. Upload files in Media Studio โ†’ Library or generate in Media Studio โ†’ Generate."

                        ewpwa_refresh_media_btn.click(
                            fn=get_media_paths_display,
                            inputs=[generated_media_paths],
                            outputs=[ewpwa_media_paths_display]
                        )

                    # Config Validation / Linting - ENHANCED with actionable fixes
                    with gr.Accordion("Validate Config (Story Linting)", open=False):
                        gr.Markdown("**Validation with actionable suggestions and auto-fix**")
                        with gr.Row():
                            ewpwa_validate_btn = gr.Button("Run Validation", variant="primary")
                            ewpwa_autofix_btn = gr.Button("Auto-Fix All Issues", variant="secondary")
                            ewpwa_mermaid_btn = gr.Button("Generate Diagram")

                        # Stats display
                        ewpwa_validation_stats = gr.Markdown(value="*Run validation to see stats*")

                        # Detailed issues with fix suggestions
                        ewpwa_validation_output = gr.Markdown(label="Validation Results")

                        # Auto-fix log
                        ewpwa_autofix_log = gr.Textbox(label="Auto-Fix Log", lines=4, visible=False)

                        ewpwa_mermaid_output = gr.Code(label="Mermaid Diagram (copy to mermaid.live)", language=None, lines=10)

                        def run_enhanced_validation(config):
                            """Run validation and return formatted results with stats."""
                            if not config:
                                return "No config loaded", "*Load a config first*"

                            validation = get_validation_with_fixes(config)
                            issues = validation["issues"]
                            stats = validation["stats"]

                            # Format stats
                            stats_md = f"""**Config Stats:** {stats.get('total_states', 0)} states | """
                            stats_md += f"""{stats.get('total_issues', 0)} issues ({stats.get('fixable_issues', 0)} auto-fixable)"""

                            if stats.get('issue_types'):
                                types_str = ", ".join([f"{k}: {v}" for k, v in stats['issue_types'].items()])
                                stats_md += f"\n*Issue types: {types_str}*"

                            # Format issues
                            issues_md = format_issues_for_display(issues)

                            return issues_md, stats_md

                        def run_autofix(config):
                            """Apply all auto-fixes and return updated config."""
                            if not config:
                                return config, "No config loaded", gr.update(visible=False)

                            fixed_config, count, log = apply_all_quick_fixes(config)

                            log_text = f"Applied {count} fixes:\n" + "\n".join(log)
                            return fixed_config, log_text, gr.update(visible=True)

                        ewpwa_validate_btn.click(
                            fn=run_enhanced_validation,
                            inputs=[ewpwacustom_config],
                            outputs=[ewpwa_validation_output, ewpwa_validation_stats]
                        )

                        ewpwa_autofix_btn.click(
                            fn=run_autofix,
                            inputs=[ewpwacustom_config],
                            outputs=[ewpwacustom_config, ewpwa_autofix_log, ewpwa_autofix_log]
                        )

                        ewpwa_mermaid_btn.click(
                            fn=generate_mermaid_diagram,
                            inputs=[ewpwacustom_config],
                            outputs=[ewpwa_mermaid_output]
                        )

                    # LLM Structure Advice
                    with gr.Accordion("Ask LLM for Structure Advice", open=False):
                        gr.Markdown("**Model:** Gemma-2-9b-it via Gradio Client (huggingface-projects/gemma-2-9b-it)")

                        # Preset prompts dropdown
                        cohesion_prompts = get_llm_cohesion_prompts()
                        ewpwa_preset_dropdown = gr.Dropdown(
                            choices=["Custom question"] + list(cohesion_prompts.keys()),
                            value="Custom question",
                            label="Preset Analysis"
                        )
                        ewpwa_llm_question = gr.Textbox(
                            label="Question about your config",
                            placeholder="e.g., How can I add branching paths? What transitions am I missing?",
                            lines=2
                        )
                        ewpwa_llm_advice_btn = gr.Button("Get Advice")
                        ewpwa_llm_response = gr.Textbox(label="LLM Response", lines=8)

                        def get_structure_advice(preset, question, config):
                            if preset != "Custom question" and preset in cohesion_prompts:
                                # Use preset prompt
                                prompt = cohesion_prompts[preset].format(config=config[:3000] if config else "No config loaded")
                            elif question:
                                prompt = f"""Analyze this game config JSON and answer the question.

Config:
{config[:2000] if config else "No config loaded"}

Question: {question}

Provide specific, actionable advice for improving the game structure."""
                            else:
                                return "Please enter a question or select a preset analysis."

                            try:
                                result = TestGradioClientrandommodel(prompt)
                                return result if result else "No response received."
                            except Exception as e:
                                return f"Error: {str(e)}"

                        ewpwa_llm_advice_btn.click(
                            fn=get_structure_advice,
                            inputs=[ewpwa_preset_dropdown, ewpwa_llm_question, ewpwacustom_config],
                            outputs=[ewpwa_llm_response]
                        )

                    # Dynamic config editor with sync capability
                    ewpwa_edit_output = gr.Textbox(label="Last Built Config (auto-applied to main)", lines=8, visible=True)

                    @gr.render(inputs=[ewpwacustom_config, generated_media_paths])
                    def render_config_editor(config_json, media_paths):
                        if not config_json:
                            gr.Markdown("*Enter JSON config on left and click 'Load Config' to start editing*")
                            return

                        try:
                            data = json.loads(config_json)
                        except json.JSONDecodeError as e:
                            gr.Markdown(f"**JSON Error:** {str(e)}")
                            return

                        # Get ALL media files from saved_media folder (uploads + generated)
                        all_media_files = get_all_media_files()

                        # Determine structure
                        if 'masterlocation1' in data:
                            locations_data = data['masterlocation1']
                            wrapper_key = 'masterlocation1'
                        else:
                            locations_data = data
                            wrapper_key = None

                        outputs = []
                        location_keys = []

                        for location, details in locations_data.items():
                            if location == 'end':
                                continue

                            location_keys.append(location)
                            desc_preview = (details.get('description', '')[:40] + '...') if len(details.get('description', '')) > 40 else details.get('description', '')

                            with gr.Accordion(f"{location}: {desc_preview}", open=False):
                                desc = gr.Textbox(label="Description", value=details.get('description', ''), lines=2, interactive=True)
                                outputs.append(desc)

                                events = gr.Textbox(label="Events", value=json.dumps(details.get('events', [])), interactive=True)
                                outputs.append(events)

                                choices = gr.Textbox(label="Choices", value=json.dumps(details.get('choices', [])), interactive=True)
                                outputs.append(choices)

                                transitions = gr.Textbox(label="Transitions", value=json.dumps(details.get('transitions', {})), interactive=True)
                                outputs.append(transitions)

                                with gr.Row():
                                    media = gr.Textbox(label="Media", value=json.dumps(details.get('media', [])), scale=2, interactive=True)
                                    if all_media_files:
                                        media_dd = gr.Dropdown(choices=all_media_files, label="Add path", scale=1, interactive=True)
                                outputs.append(media)

                                devnotes = gr.Textbox(label="Notes", value=json.dumps(details.get('developernotes', [])) if isinstance(details.get('developernotes'), list) else str(details.get('developernotes', '')), interactive=True)
                                outputs.append(devnotes)

                        if 'end' in locations_data:
                            with gr.Accordion("End State", open=False):
                                gr.JSON(value=locations_data['end'])

                        num_fields = 6

                        def build_json(*values):
                            result = {}
                            for i, loc in enumerate(location_keys):
                                try:
                                    result[loc] = {
                                        "description": values[i * num_fields],
                                        "events": json.loads(values[i * num_fields + 1]) if values[i * num_fields + 1] else [],
                                        "choices": json.loads(values[i * num_fields + 2]) if values[i * num_fields + 2] else [],
                                        "transitions": json.loads(values[i * num_fields + 3]) if values[i * num_fields + 3] else {},
                                        "media": json.loads(values[i * num_fields + 4]) if values[i * num_fields + 4] else [],
                                        "developernotes": json.loads(values[i * num_fields + 5]) if values[i * num_fields + 5].startswith('[') else values[i * num_fields + 5]
                                    }
                                except:
                                    result[loc] = {"description": values[i * num_fields], "events": [], "choices": [], "transitions": {}, "media": [], "developernotes": "parse error"}

                            if 'end' in locations_data:
                                result['end'] = locations_data['end']

                            if wrapper_key:
                                return json.dumps({wrapper_key: result}, indent=2)
                            return json.dumps(result, indent=2)

                        def build_and_sync(*values):
                            result = build_json(*values)
                            return result, result  # Return to both edit output and main config

                        sync_btn = gr.Button("Build & Apply Config", variant="primary")
                        sync_btn.click(fn=build_and_sync, inputs=outputs, outputs=[ewpwa_edit_output, ewpwacustom_config])

            # ========== EVENT HANDLERS ==========
            # Note: ewpwasubmit_btn handler moved below with enhanced state display

            ewpwacustom_configbtn.click(
                load_game,
                inputs=[ewpwacustom_config, ewpwamediabool],
                outputs=[ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia]
            )

            # Demo config loaders
            def load_sandwich_demo():
                config_json = json.dumps(SANDWICH_DEMO_CONFIG, indent=2)
                return config_json

            def load_skyrim_demo():
                config_json = json.dumps(SKYRIM_DEMO_CONFIG, indent=2)
                return config_json

            def load_big_rpg_demo():
                """Load the Big RPG Scale demo data and export it as a game config."""
                db = EntityDatabase()
                db.load_demo_data()
                return db.export_to_game_config()

            ewpwa_load_sandwich_btn.click(
                fn=load_sandwich_demo,
                outputs=[ewpwacustom_config]
            )
            ewpwa_load_skyrim_btn.click(
                fn=load_skyrim_demo,
                outputs=[ewpwacustom_config]
            )
            ewpwa_load_big_rpg_btn.click(
                fn=load_big_rpg_demo,
                outputs=[ewpwacustom_config]
            )

            # Sync edited config back to main config textbox
            ewpwasync_from_edit_btn.click(
                fn=lambda x: x,
                inputs=[ewpwa_edit_output],
                outputs=[ewpwacustom_config]
            )

            ewpgenerate_button.click(
                generate_story_and_timeline,
                inputs=[ewpgenerate_no_story_timeline_points, ewpgenerate_no_ui_timeline_points, ewptimeline_num_lists_slider, ewptimeline_items_per_list_slider, ewptimeline_include_existing_games, ewptimeline_include_multiplayer],
                outputs=[ewptimeline_output_with_assets, ewpstory_output, ewpwacustom_config, ewptimeline_output_text, ewptimeline_selected_lists_text]
            )

            # ========== NEW EVENT HANDLERS FOR ENHANCED FEATURES ==========

            # Update state dropdown when config is loaded
            def update_state_dropdown(config_json):
                """Update the jump-to-state dropdown with states from the config."""
                states, display_map = get_all_states_from_config(config_json)
                if states:
                    choices = [(display_map.get(s, s), s) for s in states]
                    return gr.update(choices=choices, value=states[0] if states else None)
                return gr.update(choices=[], value=None)

            ewpwacustom_configbtn.click(
                update_state_dropdown,
                inputs=[ewpwacustom_config],
                outputs=[ewpwa_state_dropdown]
            )

            # Jump to state handler
            def handle_jump_to_state(config_json, state_id):
                """Handle jumping to a specific state."""
                result = jump_to_state(config_json, state_id, with_media=True)
                # result is: (error_box, game_log, description, choices, config, session, media, state_display)
                return result

            ewpwa_jump_btn.click(
                handle_jump_to_state,
                inputs=[ewpwacustom_config, ewpwa_state_dropdown],
                outputs=[ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display]
            )

            # Hot reload handler
            def handle_hot_reload(config_json, game_session):
                """Handle hot reloading config while preserving game state."""
                result = hot_reload_config(config_json, game_session, with_media=True)
                # result is: (error_box, game_log, description, choices, config, session, media, state_display)
                return result

            ewpwa_hot_reload_btn.click(
                handle_hot_reload,
                inputs=[ewpwacustom_config, ewpwagame_session],
                outputs=[ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices, ewpwacustom_config, ewpwagame_session, ewpwamedia, ewpwa_current_state_display]
            )

            # Update current state display when making choices
            def make_choice_enhanced(choice, game_session, with_media):
                """Enhanced make_choice that updates state display."""
                result = make_choice_with_state_display(choice, game_session, with_media)
                # result is: (description, choices, game_log, session, media, state_display)
                return result

            ewpwasubmit_btn.click(
                make_choice_enhanced,
                inputs=[ewpwachoices, ewpwagame_session, ewpwamediabool],
                outputs=[ewpwadescription, ewpwachoices, ewpwagame_log, ewpwagame_session, ewpwamedia, ewpwa_current_state_display]
            )

            # Export playthrough log
            def handle_export_log(game_session):
                """Export the current playthrough as markdown."""
                log = export_playthrough_log(game_session)
                return log, gr.update(visible=True)

            ewpwa_export_log_btn.click(
                handle_export_log,
                inputs=[ewpwagame_session],
                outputs=[ewpwa_exported_log, ewpwa_exported_log]
            )

            # Load demo config handler
            def create_demo_loader(demo_key):
                """Create a loader function for a specific demo."""
                def load_specific_demo():
                    # Get the config based on the key
                    if demo_key == "finished_product_demo":
                        config_data = finished_product_demo
                    elif demo_key in ExampleGameConfigs:
                        config_data = ExampleGameConfigs[demo_key]
                    else:
                        return (
                            gr.update(value=f"Demo '{demo_key}' not found"),
                            None, None, gr.update(choices=[]), None, None, None,
                            "Demo not found", gr.update(choices=[], value=None)
                        )

                    config_json = json.dumps(config_data, default=lambda o: o.__dict__, indent=2)

                    # Load the game
                    result = load_game(config_json, with_media=True)

                    # Also update state dropdown
                    states, display_map = get_all_states_from_config(config_json)
                    state_choices = [(display_map.get(s, s), s) for s in states] if states else []

                    # Get current state for display
                    current_state = states[0] if states else "No states"

                    return (
                        result[0],  # error_box
                        result[1],  # game_log
                        result[2],  # description
                        result[3],  # choices
                        gr.update(value=config_json),  # config textbox
                        result[5],  # game_session
                        result[6],  # media
                        current_state,  # current_state_display
                        gr.update(choices=state_choices, value=states[0] if states else None)  # state_dropdown
                    )
                return load_specific_demo

            demo_outputs = [
                ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices,
                ewpwacustom_config, ewpwagame_session, ewpwamedia,
                ewpwa_current_state_display, ewpwa_state_dropdown
            ]

            ewpwa_demo_btn_village.click(create_demo_loader("finished_product_demo"), outputs=demo_outputs)
            ewpwa_demo_btn_racing.click(create_demo_loader("Racinggametest"), outputs=demo_outputs)
            ewpwa_demo_btn_event.click(create_demo_loader("Eventplanningstortytest"), outputs=demo_outputs)
            ewpwa_demo_btn_timeline.click(create_demo_loader("TimelineStructurePlanningAttempt"), outputs=demo_outputs)
            ewpwa_demo_btn_memory.click(create_demo_loader("MemoryFragments"), outputs=demo_outputs)
            # Stateful configs (with logic gates)
            ewpwa_demo_btn_logic.click(create_demo_loader("LogicGatesDemo"), outputs=demo_outputs)
            ewpwa_demo_btn_reference.click(create_demo_loader("StateSystemReference"), outputs=demo_outputs)

            # Template-based config generation
            def update_template_description(template_key):
                """Update template description when selection changes."""
                if template_key in NARRATIVE_TEMPLATES:
                    return NARRATIVE_TEMPLATES[template_key]["description"]
                return ""

            ewpwa_template_dropdown.change(
                update_template_description,
                inputs=[ewpwa_template_dropdown],
                outputs=[ewpwa_template_desc]
            )

            def handle_generate_from_template(template_key, theme, num_endings):
                """Generate config from selected template."""
                config = generate_config_from_template(template_key, theme, num_endings)
                # Also update the state dropdown
                states, display_map = get_all_states_from_config(config)
                choices = [(display_map.get(s, s), s) for s in states] if states else []
                return config, gr.update(choices=choices, value=states[0] if states else None)

            ewpwa_generate_template_btn.click(
                handle_generate_from_template,
                inputs=[ewpwa_template_dropdown, ewpwa_theme_dropdown, ewpwa_endings_slider],
                outputs=[ewpwacustom_config, ewpwa_state_dropdown]
            )

            # Prompt-based config generation
            def handle_generate_from_prompt(prompt, structure_type):
                """Generate config from text prompt."""
                if not prompt:
                    return "", gr.update(choices=[], value=None)
                config = generate_config_from_prompt(prompt, structure_type)
                # Also update the state dropdown
                states, display_map = get_all_states_from_config(config)
                choices = [(display_map.get(s, s), s) for s in states] if states else []
                return config, gr.update(choices=choices, value=states[0] if states else None)

            ewpwa_generate_prompt_btn.click(
                handle_generate_from_prompt,
                inputs=[ewpwa_prompt_input, ewpwa_structure_dropdown],
                outputs=[ewpwacustom_config, ewpwa_state_dropdown]
            )

            # ============================================================
            # ONE-CLICK TO GAMEPLAY EVENT HANDLERS
            # ============================================================

            def otg_start_workflow(count, inc_open, inc_tens, inc_act, inc_emo,
                                   inc_disc, inc_soc, inc_end, force_open, force_end,
                                   media_type, gen_mode, text_model, image_model):
                """Step 1: Generate sequence, queue prompts, return initial state."""
                # Clear queue and prepare
                otg_clear_and_prepare_queue()

                # Generate sequence
                list_out, json_out, prompts_out = generate_scenario_sequence(
                    count, inc_open, inc_tens, inc_act, inc_emo,
                    inc_disc, inc_soc, inc_end, force_open, force_end
                )

                if "Select at least one category" in list_out:
                    return (
                        list_out, json_out, [], "**Error:** Select at least one category",
                        gr.update(visible=True), gr.update(visible=False),
                        json_out, prompts_out
                    )

                # Add prompts to queue with section tracking
                queue_df, queue_info, status = otg_add_prompts_with_section_tracking(
                    prompts_out, json_out, media_type
                )

                return (
                    list_out, json_out, queue_df,
                    f"**Queued {len(generation_queue)} items** - Starting generation...",
                    gr.update(visible=False),  # Hide generate button
                    gr.update(visible=True),   # Show stop button
                    json_out, prompts_out
                )

            def otg_start_beat_workflow(format_type, genre, beat_count, media_type, gen_mode, text_model, image_model):
                """Story Beats workflow: Generate sequence, queue prompts, return initial state."""
                otg_clear_and_prepare_queue()

                # Generate story beat sequence
                list_out, json_out, prompts_out = generate_beat_sequence(format_type, genre, int(beat_count))

                if "Select a valid" in list_out or not json_out or json_out == "{}":
                    return (
                        list_out, json_out, [], "**Error:** Invalid format or genre selection",
                        gr.update(visible=True), gr.update(visible=False),
                        json_out, prompts_out
                    )

                # Add prompts to queue with section tracking
                queue_df, queue_info, status = otg_add_prompts_with_section_tracking(
                    prompts_out, json_out, media_type
                )

                return (
                    list_out, json_out, queue_df,
                    f"**Queued {len(generation_queue)} items** - Starting {genre} story generation...",
                    gr.update(visible=False),
                    gr.update(visible=True),
                    json_out, prompts_out
                )

            def otg_start_dnd_workflow(difficulty, encounter_count, inc_combat, inc_social,
                                        inc_exploration, inc_puzzle, inc_boss, force_boss_end,
                                        media_type, gen_mode, text_model, image_model):
                """D&D Adventure workflow: Generate sequence, queue prompts, return initial state."""
                otg_clear_and_prepare_queue()

                # Generate D&D encounter sequence
                list_out, json_out, prompts_out = generate_dnd_sequence(
                    int(encounter_count), difficulty,
                    inc_combat, inc_social, inc_exploration, inc_puzzle, inc_boss,
                    force_boss_end
                )

                if "Select at least one" in list_out or not json_out or json_out == "{}":
                    return (
                        list_out, json_out, [], "**Error:** Select at least one encounter type",
                        gr.update(visible=True), gr.update(visible=False),
                        json_out, prompts_out
                    )

                # Add prompts to queue with section tracking
                queue_df, queue_info, status = otg_add_prompts_with_section_tracking(
                    prompts_out, json_out, media_type
                )

                return (
                    list_out, json_out, queue_df,
                    f"**Queued {len(generation_queue)} items** - Starting D&D adventure generation...",
                    gr.update(visible=False),
                    gr.update(visible=True),
                    json_out, prompts_out
                )

            def otg_start_world_workflow(location_count, inc_forest, inc_mountain, inc_desert,
                                          inc_coastal, inc_urban, inc_swamp, inc_tundra, urban_start,
                                          media_type, gen_mode, text_model, image_model):
                """World Explorer workflow: Generate sequence, queue prompts, return initial state."""
                otg_clear_and_prepare_queue()

                # Generate world exploration sequence
                list_out, json_out, prompts_out = generate_world_sequence(
                    int(location_count),
                    inc_forest, inc_mountain, inc_desert, inc_coastal,
                    inc_urban, inc_swamp, inc_tundra, urban_start
                )

                if "Select at least one" in list_out or not json_out or json_out == "{}":
                    return (
                        list_out, json_out, [], "**Error:** Select at least one terrain type",
                        gr.update(visible=True), gr.update(visible=False),
                        json_out, prompts_out
                    )

                # Add prompts to queue with section tracking
                queue_df, queue_info, status = otg_add_prompts_with_section_tracking(
                    prompts_out, json_out, media_type
                )

                return (
                    list_out, json_out, queue_df,
                    f"**Queued {len(generation_queue)} items** - Starting world exploration generation...",
                    gr.update(visible=False),
                    gr.update(visible=True),
                    json_out, prompts_out
                )

            def otg_start_timeline_workflow(event_count, inc_morning, inc_midday, inc_afternoon,
                                             inc_evening, inc_night, inc_past, inc_future, chrono_order,
                                             media_type, gen_mode, text_model, image_model):
                """Timeline workflow: Generate sequence, queue prompts, return initial state."""
                otg_clear_and_prepare_queue()

                # Generate timeline sequence
                list_out, json_out, prompts_out = generate_timeline_sequence(
                    int(event_count),
                    inc_morning, inc_midday, inc_afternoon, inc_evening,
                    inc_night, inc_past, inc_future, chrono_order
                )

                if "Select at least one" in list_out or not json_out or json_out == "{}":
                    return (
                        list_out, json_out, [], "**Error:** Select at least one time period",
                        gr.update(visible=True), gr.update(visible=False),
                        json_out, prompts_out
                    )

                # Add prompts to queue with section tracking
                queue_df, queue_info, status = otg_add_prompts_with_section_tracking(
                    prompts_out, json_out, media_type
                )

                return (
                    list_out, json_out, queue_df,
                    f"**Queued {len(generation_queue)} items** - Starting timeline generation...",
                    gr.update(visible=False),
                    gr.update(visible=True),
                    json_out, prompts_out
                )

            def otg_start_song_workflow(verse_count, emotional_arc, inc_joy, inc_sorrow, inc_anger,
                                         inc_fear, inc_hope, inc_nostalgia, inc_peace,
                                         media_type, gen_mode, text_model, image_model):
                """Emotional Journey workflow: Generate sequence, queue prompts, return initial state."""
                otg_clear_and_prepare_queue()

                # Generate emotional journey sequence
                list_out, json_out, prompts_out = generate_song_sequence(
                    int(verse_count),
                    inc_joy, inc_sorrow, inc_anger, inc_fear,
                    inc_hope, inc_nostalgia, inc_peace, emotional_arc
                )

                if "Select at least one" in list_out or not json_out or json_out == "{}":
                    return (
                        list_out, json_out, [], "**Error:** Select at least one emotional category",
                        gr.update(visible=True), gr.update(visible=False),
                        json_out, prompts_out
                    )

                # Add prompts to queue with section tracking
                queue_df, queue_info, status = otg_add_prompts_with_section_tracking(
                    prompts_out, json_out, media_type
                )

                return (
                    list_out, json_out, queue_df,
                    f"**Queued {len(generation_queue)} items** - Starting emotional journey generation...",
                    gr.update(visible=False),
                    gr.update(visible=True),
                    json_out, prompts_out
                )

            def otg_start_mystery_workflow(clue_count, inc_surface, inc_shallow, inc_mid,
                                            inc_deep, inc_abyss, gradual_reveal,
                                            media_type, gen_mode, text_model, image_model):
                """Mystery workflow: Generate sequence, queue prompts, return initial state."""
                otg_clear_and_prepare_queue()

                # Generate mystery investigation sequence
                list_out, json_out, prompts_out = generate_mystery_sequence(
                    int(clue_count),
                    inc_surface, inc_shallow, inc_mid, inc_deep, inc_abyss,
                    gradual_reveal
                )

                if "Select at least one" in list_out or not json_out or json_out == "{}":
                    return (
                        list_out, json_out, [], "**Error:** Select at least one mystery layer",
                        gr.update(visible=True), gr.update(visible=False),
                        json_out, prompts_out
                    )

                # Add prompts to queue with section tracking
                queue_df, queue_info, status = otg_add_prompts_with_section_tracking(
                    prompts_out, json_out, media_type
                )

                return (
                    list_out, json_out, queue_df,
                    f"**Queued {len(generation_queue)} items** - Starting mystery investigation generation...",
                    gr.update(visible=False),
                    gr.update(visible=True),
                    json_out, prompts_out
                )

            def otg_process_and_load(gen_mode, text_model, image_model, config_json):
                """Step 2: Process queue items and auto-load when complete."""
                # Use the generator to process items
                for progress_text, current_item, queue_df, is_complete, final_config, error_details in otg_process_queue_generator(
                    gen_mode, text_model, image_model,
                    use_rag=False, use_streaming=False,
                    api_source="HF Inference", hf_model_id="", replicate_model=""
                ):
                    if is_complete:
                        # All done - load config into playtest (even with partial results)
                        if final_config and final_config.strip():
                            try:
                                # Load into playtest with updated media paths
                                result = load_game(final_config, True)
                                states, display_map = get_all_states_from_config(final_config)
                                state_choices = [(display_map.get(s, s), s) for s in states] if states else []

                                # Add error details to progress if any
                                display_progress = progress_text
                                if error_details:
                                    display_progress += f"\n\nErrors:\n{error_details}"

                                yield (
                                    display_progress, queue_df,
                                    gr.update(visible=True),  # Show generate button
                                    gr.update(visible=False), # Hide stop button
                                    final_config,  # Update config preview with new file paths
                                    # Playtest outputs
                                    result[0], result[1], result[2], result[3],
                                    final_config, result[5], result[6],
                                    states[0] if states else "No game loaded",
                                    gr.update(choices=state_choices, value=states[0] if states else None)
                                )
                            except Exception as e:
                                # Error loading config - still show the updated config
                                error_msg = f"{progress_text}\n\n**Error loading game:** {str(e)}"
                                yield (
                                    error_msg, queue_df,
                                    gr.update(visible=True),
                                    gr.update(visible=False),
                                    final_config,  # Show updated config even on error
                                    gr.update(value=f"Error: {str(e)}"), gr.update(), gr.update(), gr.update(),
                                    final_config, gr.update(), gr.update(),
                                    gr.update(), gr.update()
                                )
                        else:
                            # No config generated (all items failed)
                            error_msg = progress_text
                            if error_details:
                                error_msg += f"\n\nErrors:\n{error_details}"
                            yield (
                                error_msg, queue_df,
                                gr.update(visible=True),
                                gr.update(visible=False),
                                gr.update(),  # No config to show
                                gr.update(value="Generation failed - no assets created"), gr.update(), gr.update(), gr.update(),
                                gr.update(), gr.update(), gr.update(),
                                gr.update(), gr.update()
                            )
                        return
                    else:
                        # Still processing - yield progress update
                        yield (
                            progress_text, queue_df,
                            gr.update(), gr.update(),
                            gr.update(),  # Config preview unchanged during processing
                            gr.update(), gr.update(), gr.update(), gr.update(),
                            gr.update(), gr.update(), gr.update(),
                            gr.update(), gr.update()
                        )

            def otg_handle_stop():
                """Stop the workflow and show partial results with updated config."""
                progress_text, queue_df, partial_config = otg_stop_workflow()
                return (
                    progress_text, queue_df,
                    gr.update(visible=True),  # Show generate button
                    gr.update(visible=False), # Hide stop button
                    partial_config if partial_config else gr.update()  # Update config preview with partial results
                )

            # Wire up the main workflow
            otg_generate_btn.click(
                otg_start_workflow,
                inputs=[
                    otg_count, otg_opening, otg_tension, otg_action, otg_emotional,
                    otg_discovery, otg_social, otg_ending, otg_force_opening, otg_force_ending,
                    otg_media_type, otg_gen_mode, otg_text_model, otg_image_model
                ],
                outputs=[
                    otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md,
                    otg_generate_btn, otg_stop_btn,
                    otg_generated_config, otg_prompts_text
                ]
            ).then(
                otg_process_and_load,
                inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config],
                outputs=[
                    otg_progress_md, otg_queue_display,
                    otg_generate_btn, otg_stop_btn,
                    otg_config_preview,  # Update config preview with new file paths
                    # Playtest outputs for auto-load
                    ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices,
                    ewpwacustom_config, ewpwagame_session, ewpwamedia,
                    ewpwa_current_state_display, ewpwa_state_dropdown
                ]
            )

            otg_stop_btn.click(
                otg_handle_stop,
                outputs=[otg_progress_md, otg_queue_display, otg_generate_btn, otg_stop_btn, otg_config_preview]
            )

            # Story Beats generate button
            otg_beat_generate_btn.click(
                otg_start_beat_workflow,
                inputs=[
                    otg_beat_format, otg_beat_genre, otg_beat_count,
                    otg_media_type, otg_gen_mode, otg_text_model, otg_image_model
                ],
                outputs=[
                    otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md,
                    otg_beat_generate_btn, otg_stop_btn,
                    otg_generated_config, otg_prompts_text
                ]
            ).then(
                otg_process_and_load,
                inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config],
                outputs=[
                    otg_progress_md, otg_queue_display,
                    otg_beat_generate_btn, otg_stop_btn,
                    otg_config_preview,
                    ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices,
                    ewpwacustom_config, ewpwagame_session, ewpwamedia,
                    ewpwa_current_state_display, ewpwa_state_dropdown
                ]
            )

            # D&D Adventure generate button
            otg_dnd_generate_btn.click(
                otg_start_dnd_workflow,
                inputs=[
                    otg_dnd_difficulty, otg_dnd_count,
                    otg_dnd_combat, otg_dnd_social, otg_dnd_exploration, otg_dnd_puzzle,
                    otg_dnd_boss, otg_dnd_force_boss_end,
                    otg_media_type, otg_gen_mode, otg_text_model, otg_image_model
                ],
                outputs=[
                    otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md,
                    otg_dnd_generate_btn, otg_stop_btn,
                    otg_generated_config, otg_prompts_text
                ]
            ).then(
                otg_process_and_load,
                inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config],
                outputs=[
                    otg_progress_md, otg_queue_display,
                    otg_dnd_generate_btn, otg_stop_btn,
                    otg_config_preview,
                    ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices,
                    ewpwacustom_config, ewpwagame_session, ewpwamedia,
                    ewpwa_current_state_display, ewpwa_state_dropdown
                ]
            )

            # World Explorer generate button
            otg_world_generate_btn.click(
                otg_start_world_workflow,
                inputs=[
                    otg_world_count,
                    otg_world_forest, otg_world_mountain, otg_world_desert, otg_world_coastal,
                    otg_world_urban, otg_world_swamp, otg_world_tundra, otg_world_urban_start,
                    otg_media_type, otg_gen_mode, otg_text_model, otg_image_model
                ],
                outputs=[
                    otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md,
                    otg_world_generate_btn, otg_stop_btn,
                    otg_generated_config, otg_prompts_text
                ]
            ).then(
                otg_process_and_load,
                inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config],
                outputs=[
                    otg_progress_md, otg_queue_display,
                    otg_world_generate_btn, otg_stop_btn,
                    otg_config_preview,
                    ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices,
                    ewpwacustom_config, ewpwagame_session, ewpwamedia,
                    ewpwa_current_state_display, ewpwa_state_dropdown
                ]
            )

            # Timeline generate button
            otg_timeline_generate_btn.click(
                otg_start_timeline_workflow,
                inputs=[
                    otg_timeline_count,
                    otg_timeline_morning, otg_timeline_midday, otg_timeline_afternoon,
                    otg_timeline_evening, otg_timeline_night, otg_timeline_past, otg_timeline_future,
                    otg_timeline_chrono,
                    otg_media_type, otg_gen_mode, otg_text_model, otg_image_model
                ],
                outputs=[
                    otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md,
                    otg_timeline_generate_btn, otg_stop_btn,
                    otg_generated_config, otg_prompts_text
                ]
            ).then(
                otg_process_and_load,
                inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config],
                outputs=[
                    otg_progress_md, otg_queue_display,
                    otg_timeline_generate_btn, otg_stop_btn,
                    otg_config_preview,
                    ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices,
                    ewpwacustom_config, ewpwagame_session, ewpwamedia,
                    ewpwa_current_state_display, ewpwa_state_dropdown
                ]
            )

            # Emotional Journey generate button
            otg_song_generate_btn.click(
                otg_start_song_workflow,
                inputs=[
                    otg_song_count, otg_song_arc,
                    otg_song_joy, otg_song_sorrow, otg_song_anger, otg_song_fear,
                    otg_song_hope, otg_song_nostalgia, otg_song_peace,
                    otg_media_type, otg_gen_mode, otg_text_model, otg_image_model
                ],
                outputs=[
                    otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md,
                    otg_song_generate_btn, otg_stop_btn,
                    otg_generated_config, otg_prompts_text
                ]
            ).then(
                otg_process_and_load,
                inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config],
                outputs=[
                    otg_progress_md, otg_queue_display,
                    otg_song_generate_btn, otg_stop_btn,
                    otg_config_preview,
                    ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices,
                    ewpwacustom_config, ewpwagame_session, ewpwamedia,
                    ewpwa_current_state_display, ewpwa_state_dropdown
                ]
            )

            # Mystery generate button
            otg_mystery_generate_btn.click(
                otg_start_mystery_workflow,
                inputs=[
                    otg_mystery_count,
                    otg_mystery_surface, otg_mystery_shallow, otg_mystery_mid,
                    otg_mystery_deep, otg_mystery_abyss, otg_mystery_gradual,
                    otg_media_type, otg_gen_mode, otg_text_model, otg_image_model
                ],
                outputs=[
                    otg_sequence_preview, otg_config_preview, otg_queue_display, otg_progress_md,
                    otg_mystery_generate_btn, otg_stop_btn,
                    otg_generated_config, otg_prompts_text
                ]
            ).then(
                otg_process_and_load,
                inputs=[otg_gen_mode, otg_text_model, otg_image_model, otg_generated_config],
                outputs=[
                    otg_progress_md, otg_queue_display,
                    otg_mystery_generate_btn, otg_stop_btn,
                    otg_config_preview,
                    ewpwaerror_box, ewpwagame_log, ewpwadescription, ewpwachoices,
                    ewpwacustom_config, ewpwagame_session, ewpwamedia,
                    ewpwa_current_state_display, ewpwa_state_dropdown
                ]
            )

            # Export config with media files as zip
            def otg_export_config_with_media(config_json):
                """Export the generated config and all media files as a zip."""
                if not config_json or not config_json.strip():
                    return None, "No config to export. Generate a sequence first."

                try:
                    import tempfile
                    import zipfile
                    from datetime import datetime

                    # Parse config to find media files
                    config = json.loads(config_json)
                    media_files = []

                    # Extract all media paths from config
                    for location_key, location_data in config.items():
                        if isinstance(location_data, dict):
                            for state_key, state_data in location_data.items():
                                if isinstance(state_data, dict) and 'media' in state_data:
                                    media_list = state_data.get('media', [])
                                    if isinstance(media_list, list):
                                        media_files.extend(media_list)

                    # Create zip file
                    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                    zip_filename = f"game_export_{timestamp}.zip"
                    zip_path = os.path.join(tempfile.gettempdir(), zip_filename)

                    files_included = 0
                    files_missing = []

                    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                        # Add config JSON (named "config.json" for import compatibility)
                        zipf.writestr("config.json", config_json)

                        # Add media files to root (not in media/ subfolder) for import compatibility
                        for media_path in media_files:
                            if media_path and isinstance(media_path, str):
                                # Check if file exists
                                if os.path.exists(media_path):
                                    # Add to zip root with just filename
                                    arcname = os.path.basename(media_path)
                                    zipf.write(media_path, arcname)
                                    files_included += 1
                                else:
                                    files_missing.append(media_path)

                    # Build status message
                    status = f"Exported: {zip_filename}\n"
                    status += f"- Config: config.json\n"
                    status += f"- Media files: {files_included} included"
                    if files_missing:
                        status += f"\n- Missing files: {len(files_missing)} ({', '.join(files_missing[:3])}{'...' if len(files_missing) > 3 else ''})"

                    return zip_path, status

                except json.JSONDecodeError as e:
                    return None, f"Invalid JSON: {str(e)}"
                except Exception as e:
                    return None, f"Export error: {str(e)}"

            otg_export_btn.click(
                otg_export_config_with_media,
                inputs=[otg_config_preview],
                outputs=[otg_export_file, otg_export_status]
            )

            # AI Prompt Generation Function
            def generate_ai_assistance_prompt(config_json, prompt_type, focus_area):
                """Generate a context-aware prompt for AI chat assistance."""
                if not config_json or not config_json.strip() or config_json == "{}":
                    return "Please generate a config first before creating an AI assistance prompt."

                # Auto-detect config type from content
                detected_type = prompt_type
                if prompt_type == "auto":
                    config_lower = config_json.lower()
                    if "world" in config_lower or "location_" in config_lower or "terrain" in config_lower:
                        detected_type = "world"
                    elif "timeline" in config_lower or "event_" in config_lower or "morning" in config_lower or "evening" in config_lower:
                        detected_type = "timeline"
                    elif "emotional_journey" in config_lower or "moment_" in config_lower or "feeling" in config_lower:
                        detected_type = "song"
                    elif "investigation" in config_lower or "clue_" in config_lower or "mystery" in config_lower:
                        detected_type = "mystery"
                    elif "adventure" in config_lower or "encounter_" in config_lower or "combat" in config_lower or "dungeon" in config_lower:
                        detected_type = "dnd"
                    elif "scene_" in config_lower or "film" in config_lower or "camera" in config_lower:
                        detected_type = "film"
                    elif "beat_" in config_lower or "act_" in config_lower:
                        detected_type = "beats"
                    else:
                        detected_type = "film"  # Default fallback

                # Type-specific instructions
                type_instructions = {
                    "world": """This is a WORLD/GEOGRAPHY exploration game config. The story unfolds through location discovery.

Key aspects to enhance:
- Each location should have distinct atmosphere and secrets
- Connections between locations should feel natural (paths, rivers, roads)
- Hidden areas reward thorough exploration
- NPCs should have reasons to be in specific locations
- Environmental storytelling through descriptions""",

                    "timeline": """This is a TIMELINE/CHRONOLOGICAL narrative config. Events unfold in time sequence.

Key aspects to enhance:
- Each time period should have distinct mood (morning hope, night danger)
- Cause and effect between events should be clear
- Flashbacks/flash-forwards should reveal crucial information
- Pacing should alternate between action and reflection
- Time pressure can create tension""",

                    "song": """This is an EMOTIONAL JOURNEY config based on musical/lyrical structure.

Key aspects to enhance:
- Emotional transitions should feel earned, not jarring
- Verses build detail, choruses reinforce themes
- The bridge should offer a perspective shift
- Sensory details anchor abstract emotions
- The arc should have a satisfying resolution""",

                    "mystery": """This is a MYSTERY/INVESTIGATION config using the iceberg model (surface to deep truths).

Key aspects to enhance:
- Surface clues should be obvious but misleading
- Each layer should recontextualize previous discoveries
- Red herrings should be plausible but distinguishable
- The core truth should be surprising yet inevitable
- Character motivations drive the mystery""",

                    "dnd": """This is a D&D/FANTASY ADVENTURE config with encounters and exploration.

Key aspects to enhance:
- Combat encounters need tactical variety
- Social encounters should have multiple resolution paths
- Treasure and rewards should feel earned
- Boss encounters should be memorable set pieces
- Rest points allow strategic resource management""",

                    "film": """This is a FILM/VIDEO SCENES config structured around visual storytelling.

Key aspects to enhance:
- Each scene needs a clear visual hook
- Camera direction implies emotional tone
- Transitions between scenes should be motivated
- Dialogue should reveal character through subtext
- Visual motifs can recur for thematic resonance""",

                    "beats": """This is a STORY BEATS config following professional screenplay structure.

Key aspects to enhance:
- Each beat should turn the story in a new direction
- Character decisions should drive plot, not coincidence
- Stakes should escalate through the midpoint
- The dark night of the soul needs emotional weight
- The climax should pay off earlier setups"""
                }

                # Focus area instructions
                focus_instructions = {
                    "balanced": """Improve the config with balanced attention to:
- Richer descriptions (2-3 sentences per state)
- 3-4 meaningful choices per state where appropriate
- Clear character motivations
- Environmental details that support the mood""",

                    "detail": """Focus on ADDING DETAIL to descriptions:
- Expand each description to 3-4 vivid sentences
- Include sensory details (sight, sound, smell, touch)
- Add atmospheric elements (weather, lighting, ambient sounds)
- Include small environmental storytelling details
- Make locations feel lived-in and real""",

                    "choices": """Focus on ADDING MORE CHOICES and branches:
- Ensure each state has 3-4 distinct choices
- Add choices that reflect different playstyles (cautious, bold, clever)
- Include hidden or conditional choices
- Create meaningful branches that reconverge later
- Add optional side paths that reward exploration""",

                    "characters": """Focus on DEEPENING CHARACTER MOTIVATIONS:
- Give NPCs clear wants, fears, and secrets
- Add dialogue that reveals personality
- Create relationship dynamics between characters
- Include character-specific choices and reactions
- Show character growth through the narrative""",

                    "environment": """Focus on ENVIRONMENTAL STORYTELLING:
- Add details that imply history without exposition
- Include objects that tell stories (old letters, worn paths, abandoned items)
- Use weather and time of day to set mood
- Create spaces that feel connected to events
- Add discoverable lore through exploration""",

                    "tension": """Focus on INCREASING DRAMATIC TENSION:
- Add time pressure or urgency where appropriate
- Include moments of difficult moral choice
- Create setbacks that raise stakes
- Add foreshadowing of dangers
- Include moments of false safety before reveals"""
                }

                # Count states in config
                try:
                    config = json.loads(config_json)
                    state_count = 0
                    for section in config.values():
                        if isinstance(section, dict):
                            state_count += len(section)
                except:
                    state_count = "unknown"

                # Build the prompt
                prompt = f"""I have a game config JSON for an interactive narrative game. Please help me improve and expand it.

**CONFIG TYPE:** {detected_type.upper()}
**CURRENT SIZE:** {state_count} states
**FOCUS:** {focus_area.replace('_', ' ').title()}

{type_instructions.get(detected_type, type_instructions['film'])}

{focus_instructions.get(focus_area, focus_instructions['balanced'])}

**IMPORTANT RULES:**
1. Return ONLY valid JSON - no explanations before or after
2. Keep the exact same structure (location > state > properties)
3. Every state MUST have: "description", "choices" (list), "transitions" (dict mapping choices to state IDs)
4. Do NOT rename existing state IDs - only add new ones
5. Ensure all transitions point to valid state IDs
6. Keep "media" and "media_prompt" fields if present

**HERE IS MY CURRENT CONFIG:**
```json
{config_json}
```

Please return an improved version of this config with the enhancements described above. Remember: ONLY return valid JSON, nothing else."""

                return prompt

            otg_generate_prompt_btn.click(
                generate_ai_assistance_prompt,
                inputs=[otg_config_preview, otg_prompt_type, otg_prompt_focus],
                outputs=[otg_ai_prompt_output]
            )

        # ==================== GAME PREVIEW TABS (Moved from Portability) ====================
        with gr.Tab("Game Preview (2D)"):
            gr.Markdown("### 2D MovingDotSpace Preview")
            gr.Markdown("Generate a 2D top-down exploration game from your config.")

            with gr.Row():
                preview_2d_config = gr.Textbox(
                    label="Game Config JSON",
                    lines=8,
                    placeholder='{"village": {"start": {"description": "You arrive.", "choices": ["Enter tavern"], "transitions": {"Enter tavern": "tavern"}}}}',
                    scale=3
                )
                with gr.Column(scale=1):
                    preview_2d_demo_btn = gr.Button("Load Demo Config", variant="secondary")
                    preview_2d_generate_btn = gr.Button("Generate & Test", variant="primary")

            preview_2d_status = gr.Markdown("")
            gr.Markdown("### Game Preview (click inside to focus, use arrow keys to move)")
            preview_2d_html = gr.HTML(
                value='<div style="width:100%;height:600px;border:2px dashed #ccc;display:flex;align-items:center;justify-content:center;background:#1a1a2e;color:#888;border-radius:8px;">Click "Generate & Test" to preview your game here</div>',
                label="Game Preview"
            )

            with gr.Accordion("Generated HTML Code (copy to save)", open=False):
                preview_2d_code = gr.Code(label="HTML Source", language="html", lines=15)

            def load_2d_demo():
                import os
                try:
                    demo_path = os.path.join(os.path.dirname(__file__), "sandwich_quest_demo.json")
                    with open(demo_path, 'r', encoding='utf-8') as f:
                        return f.read()
                except:
                    return '{"village": {"start": {"description": "Demo village.", "choices": ["Explore"], "transitions": {"Explore": "village_explore"}}}}'

            def generate_2d_preview(config_json):
                if not config_json or not config_json.strip():
                    return "Please provide config JSON", '<div style="width:100%;height:600px;border:2px dashed #ccc;display:flex;align-items:center;justify-content:center;background:#1a1a2e;color:#888;">Please provide a game config JSON</div>', ""
                try:
                    from exporters import export_to_movingdotspace
                    explanation, html_code = export_to_movingdotspace(config_json)
                    if html_code:
                        import base64
                        html_b64 = base64.b64encode(html_code.encode('utf-8')).decode('utf-8')
                        iframe_html = f'<iframe src="data:text/html;base64,{html_b64}" style="width:100%;height:600px;border:2px solid #4CAF50;border-radius:8px;"></iframe>'
                        return f"Generated! {explanation}", iframe_html, html_code
                    return f"Failed: {explanation}", '<div style="color:red;">Generation failed</div>', ""
                except Exception as e:
                    return f"Error: {str(e)}", f'<div style="color:red;">Error: {str(e)}</div>', ""

            preview_2d_demo_btn.click(fn=load_2d_demo, outputs=[preview_2d_config])
            preview_2d_generate_btn.click(
                fn=generate_2d_preview,
                inputs=[preview_2d_config],
                outputs=[preview_2d_status, preview_2d_html, preview_2d_code]
            )

        with gr.Tab("Game Preview (3D)"):
            gr.Markdown("### 3D PlayCanvas Preview")
            gr.Markdown("Preview your game config as a 3D WebGL scene.")

            with gr.Row():
                preview_3d_config = gr.Textbox(
                    label="Game Config JSON",
                    lines=8,
                    placeholder="Paste your game config JSON here...",
                    scale=3
                )
                with gr.Column(scale=1):
                    preview_3d_demo_btn = gr.Button("Load Demo Config", variant="secondary")
                    preview_3d_generate_btn = gr.Button("Generate 3D Preview", variant="primary")

            preview_3d_status = gr.Markdown("")
            preview_3d_html = gr.HTML(
                value='<div style="width:100%;height:600px;border:2px dashed #ccc;display:flex;align-items:center;justify-content:center;background:#1a1a2e;color:#888;border-radius:8px;">Click "Generate 3D Preview" to see your game</div>',
                label="3D Preview"
            )

            with gr.Accordion("Generated HTML Code", open=False):
                preview_3d_code = gr.Code(label="HTML Source", language="html", lines=15)

            def load_3d_demo():
                return '{"castle": {"entrance": {"description": "A grand castle entrance.", "choices": ["Enter", "Leave"], "transitions": {"Enter": "castle_hall", "Leave": "forest"}}}}'

            def generate_3d_preview(config_json):
                if not config_json or not config_json.strip():
                    return "Please provide config JSON", '<div style="width:100%;height:600px;border:2px dashed #ccc;display:flex;align-items:center;justify-content:center;background:#1a1a2e;color:#888;">Please provide a game config JSON</div>', ""
                try:
                    from exporters import export_to_playcanvas_html
                    explanation, html_code = export_to_playcanvas_html(config_json)
                    if html_code:
                        import base64
                        html_b64 = base64.b64encode(html_code.encode('utf-8')).decode('utf-8')
                        iframe_html = f'<iframe src="data:text/html;base64,{html_b64}" style="width:100%;height:600px;border:2px solid #4CAF50;border-radius:8px;"></iframe>'
                        return f"Generated! {explanation}", iframe_html, html_code
                    return f"Failed: {explanation}", '<div style="color:red;">Generation failed</div>', ""
                except Exception as e:
                    return f"Error: {str(e)}", f'<div style="color:red;">Error: {str(e)}</div>', ""

            preview_3d_demo_btn.click(fn=load_3d_demo, outputs=[preview_3d_config])
            preview_3d_generate_btn.click(
                fn=generate_3d_preview,
                inputs=[preview_3d_config],
                outputs=[preview_3d_status, preview_3d_html, preview_3d_code]
            )

        # ==================== D&D GAME MASTER (Moved from Config Dev) ====================
        create_dnd_gm_tab()

        # ==================== CONFIG ANALYSIS & IMPROVEMENT (Merged Tab) ====================
        create_config_analysis_tab()

        create_llm_playtest_tab(modelnames)

    with gr.Tab("Config Development Assistance"):
        gr.Markdown("## Config Development Assistance")
        gr.Markdown("Tools and references for creating game configs. Full design theory available in the Design Reference Guide below.")

        # ==================== STARTING CONSIDERATIONS ====================
        gr.Markdown("""
### Starting Considerations - Where to Begin?
Every game config can begin from different creative angles. Pick the approach that matches your inspiration:
        """)

        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("""
**๐ŸŒ World Facts / Geography**

Start with locations, regions, and how they connect. Build the world first, then populate it.

โ†’ **Big RPG Scale** tab โ†’ Locations
                """)
            with gr.Column(scale=1):
                gr.Markdown("""
**๐ŸŽฌ Video/Film Ideas (Writer)**

Structure your story using professional beat templates for 90-min films, 30-min TV episodes, or 9-min YouTube videos.

โ†’ **Story Architect** tab
                """)
            with gr.Column(scale=1):
                gr.Markdown("""
**๐Ÿ“น Video/Film Ideas (Videographer)**

Start from camera angles, shot composition, visual grammar, and direction notes. Think visually first.

โ†’ **Story Architect** tab โ†’ Visual Grammar
                """)

        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("""
**๐ŸŽต Song / Lyric Ideas**

Transform emotional music or poetry into journey-based games. Each verse becomes a location or mood.

โ†’ **Source Content to Games** tab
                """)
            with gr.Column(scale=1):
                gr.Markdown("""
**โฑ๏ธ Timeline Events**

Build narrative beats positioned on a visual timeline. Great for story-driven games with clear progression.

โ†’ **Story Graph** tab or **Generate Config** โ†’ Timeline Generator
                """)
            with gr.Column(scale=1):
                gr.Markdown("""
**๐Ÿ“š Existing Structures**

Use D&D monsters/items, story templates, or classic narrative structures as building blocks.

โ†’ **D&D 5e SRD** tab, **Mermaid Diagrams** tab
                """)

        with gr.Row():
            with gr.Column(scale=1):
                gr.Markdown("""
**๐Ÿง  Character Psychology**

Create deeply motivated characters that drive the story. Define wants, flaws, and psychological profiles.

โ†’ **Narrative Engine** tab โ†’ Character Generator
                """)
            with gr.Column(scale=1):
                gr.Markdown("""
**๐Ÿ”ฎ Mystery / Hidden Depth**

Layer information with surface events hiding deeper truths. Use the 5-layer iceberg model.

โ†’ **Narrative Engine** tab โ†’ Mystery Layers
                """)
            with gr.Column(scale=1):
                gr.Markdown("""
**โš”๏ธ Faction Politics**

Design allegiances, hierarchies, and reputation systems. Build conflict through competing groups.

โ†’ **Big RPG Scale** tab โ†’ Factions
                """)

        # ==================== DESIGN REFERENCE GUIDE ====================
        # Random tips data for randomiser
        DESIGN_TIPS = {
            "core": [
                "Make story-based games using mechanics-based games (Chess, Poker, Sudoku) as a conduit",
                "Sometimes a fun game includes unfairness - Elden Ring uses controls and movement restrictions",
                "Minimise the cost of exploration so players can explore more (Jonas Tyroller)",
                "Every theme can be turned into a battle story (resource accumulation across a map)",
                "Story structure: Ending Conditions โ†’ Villain โ†’ Travel/Politics/Combat โ†’ Characters",
                "A game is alive when the same decisions won't work over and over",
                "Boss fights create memorable moments through controlled unfairness",
                "The best games teach mechanics through play, not tutorials",
                "Stakes make choices matter - what can the player lose?",
                "Pacing is about alternating tension and release"
            ],
            "blocks": [
                "Locations: Jungle, Sea, Desert, Snow, City, Village, Space - each has unique mood",
                "Character Relations: Friend or foe - but the best stories blur this line",
                "Conflict Origins: Betrayal, lack of sympathy, unfair expectations, misinterpretation",
                "GTA Heists: Replayability through overlapping branching narratives",
                "Tekken: 2/3 mistakes = lost round (casino-style stakes)",
                "Elden Ring: Storytelling by traversal of map, environmental narrative",
                "Battlefront: Elites amongst Commoners creates power fantasy variation",
                "Purpose: Unpredictable Nuances, Simulation, Time capsule, Tangible Metaphor",
                "Every location should have a secret or hidden element",
                "NPCs should have their own goals, not just serve the player"
            ],
            "workflow": [
                "Timeline: Mermaid Diagram โ†’ Story โ†’ Initial JSON โ†’ Corrections โ†’ Media โ†’ Assets",
                "Remix an existing config to learn the format quickly",
                "Ask LLM to generate, then manually fix edge cases",
                "Endless combination testing reveals unexpected interactions",
                "Write by hand with format assistance for full control",
                "Test early, test often - broken configs are harder to fix later",
                "Keep a library of working configs as templates",
                "Version control your configs - git is your friend",
                "Document your design decisions for future reference",
                "Playtest with fresh eyes after a break"
            ]
        }

        def get_random_design_tip():
            """Get random tips from each category."""
            import random
            core = random.choice(DESIGN_TIPS["core"])
            blocks = random.choice(DESIGN_TIPS["blocks"])
            workflow = random.choice(DESIGN_TIPS["workflow"])
            return f"**๐ŸŽฒ Random Design Tips:**\n\n**Core:** {core}\n\n**Building Block:** {blocks}\n\n**Workflow:** {workflow}"

        with gr.Accordion("Design Reference Guide (Theory & Ideas)", open=False):
            gr.Markdown("*Full design theory, game fundamentals, and workflow documentation.*")

            with gr.Row():
                random_tip_btn = gr.Button("๐ŸŽฒ Random Tips", variant="secondary", size="sm")
            random_tip_output = gr.Markdown("")

            random_tip_btn.click(fn=get_random_design_tip, outputs=[random_tip_output])

            with gr.Accordion("Core Principles", open=False):
                gr.Markdown("""
**End Goal:** Make story-based games using mechanics-based games (Chess, Poker, Sudoku, Rubiks Cube, etc.) as a conduit.

**Key Ideas:**
- Sometimes a fun game includes unfairness - Elden Ring (Controls and movement restrictions), Boss fights
- Minimise the cost of exploration so you can explore more ([Jonas Tyroller](https://youtu.be/o5K0uqhxgsE))
- Every theme can be turned into a battle story (resource accumulation across a map)
- Story structure: Ending Conditions โ†’ Main Villain/Antagonist โ†’ Travel, Politics, Combat โ†’ Characters
- A game is alive when the same decisions won't work over and over
                """)

            with gr.Accordion("Story Building Blocks", open=False):
                gr.Markdown("""
**Locations:** Jungle, Sea, Desert, Snow, City, Village, Space

**Character Relations:** Friend or foe

**Conflict Origins:** Betrayal, lack of sympathy, unfair expectations, misinterpretation of actions

**Purpose Types:** Unpredictable Nuances, Simulation, Time capsule, Tangible Metaphor, Song Concept, Advert as game

**Structural Inspirations:**
- GTA Heists - Replayability and stakes, overlapping branching narratives
- Tekken - 2/3 mistakes = lost round (casino-style stakes)
- Elden Ring - Storytelling by traversal of map
- Battlefront - Elites amongst Commoners
                """)

            with gr.Accordion("Workflow Overview", open=False):
                gr.Markdown("""
**Timeline Workflow:**
1. [Pre-creation] Mermaid Diagram โ†’ Story
2. [Creation] Initial JSON (LLM + manual fixes)
3. [Post-creation] JSON Corrections โ†’ Media prompts โ†’ Asset Generation โ†’ JSON Media population

**Config Writing Approaches:**
- Remix an existing config
- Ask LLM to generate one
- Endless combination testing
- Write by hand with format assistance
                """)

        # ==================== GENERATE CONFIG TAB ====================
        with gr.Tab("Generate Config"):
            gr.Markdown("### Config Generation Tools")

            with gr.Accordion("Timeline Generator", open=True):
                gr.Markdown("Generate a random timeline and story based on UI elements and story events. Use this as a starting point for LLM refinement.")
                with gr.Row():
                    cda_timeline_output = gr.Textbox(label="Generated Timeline", lines=15)
                    cda_story_output = gr.Textbox(label="Generated Story", lines=15)
                with gr.Row():
                    cda_config_output = gr.Code(label="Generated Config JSON", language="json", lines=10)
                with gr.Row():
                    cda_story_points = gr.Slider(minimum=1, value=10, step=1, maximum=30, label="Story Points")
                    cda_ui_points = gr.Slider(minimum=1, value=10, step=1, maximum=30, label="UI Points")
                with gr.Row():
                    cda_num_lists = gr.Slider(minimum=1, maximum=len(all_idea_lists), step=1, label="Idea Lists to Use", value=3)
                    cda_items_per_list = gr.Slider(minimum=1, maximum=10, step=1, label="Items per List", value=3)
                with gr.Row():
                    cda_include_games = gr.Checkbox(label="Include Game Inspirations", value=True)
                    cda_include_multiplayer = gr.Checkbox(label="Include Multiplayer Features", value=True)
                with gr.Row():
                    cda_randomise_btn = gr.Button("๐ŸŽฒ Randomise All", variant="secondary")
                    cda_generate_btn = gr.Button("Generate Story and Timeline", variant="primary")

                def randomise_timeline_settings():
                    """Randomise all Timeline Generator settings."""
                    import random
                    return (
                        random.randint(5, 25),  # story_points
                        random.randint(5, 25),  # ui_points
                        random.randint(1, min(5, len(all_idea_lists))),  # num_lists
                        random.randint(2, 7),  # items_per_list
                        random.choice([True, False]),  # include_games
                        random.choice([True, False])  # include_multiplayer
                    )

                cda_randomise_btn.click(
                    fn=randomise_timeline_settings,
                    outputs=[cda_story_points, cda_ui_points, cda_num_lists, cda_items_per_list, cda_include_games, cda_include_multiplayer]
                )

                with gr.Row():
                    cda_suggestions = gr.Textbox(label="Random Suggestions", lines=5)
                    cda_selected_lists = gr.Textbox(label="Selected Idea Lists", lines=2)

                cda_generate_btn.click(
                    generate_story_and_timeline,
                    inputs=[cda_story_points, cda_ui_points, cda_num_lists, cda_items_per_list, cda_include_games, cda_include_multiplayer],
                    outputs=[cda_timeline_output, cda_story_output, cda_config_output, cda_suggestions, cda_selected_lists]
                )

            with gr.Accordion("Narrative Construction Tool (tnct)", open=False):
                gr.Markdown("Build narratives using character relationships and interpersonal events.")
                tnct_ui()

            with gr.Accordion("Worldbuilding - Bible Stories as Templates", open=False):
                bible_story_elements()

        # ==================== STORY GRAPH TAB (Config Development Device) ====================
        create_story_graph_tab()

        # ==================== BIG RPG SCALE TAB (Config Development Device) ====================
        create_big_rpg_scale_tab()

        # ==================== MERMAID DIAGRAMS TAB ====================
        with gr.Tab("Mermaid Diagrams"):
            gr.Markdown("### Visual Story Structure Planning")
            gr.Markdown("Use Mermaid diagrams to plan your story structure before converting to JSON config.")

            def get_random_mermaid_template():
                """Get a random mermaid template from either story structures or concept blending."""
                import random
                all_templates = {**mermaidstorystructures, **examplemermaidconceptblendingstrutures}
                name = random.choice(list(all_templates.keys()))
                return f"**{name}**", all_templates[name]

            with gr.Row():
                cda_mermaid_random_btn = gr.Button("๐ŸŽฒ Random Template", variant="secondary")
                cda_mermaid_load_btn = gr.Button("Load Mermaid.live Editor", variant="primary")

            cda_random_template_name = gr.Markdown("*Click 'Random Template' to see a random story structure*")
            cda_random_template_code = gr.Code(label="Random Template", language=None, lines=10)

            cda_mermaid_random_btn.click(
                fn=get_random_mermaid_template,
                outputs=[cda_random_template_name, cda_random_template_code]
            )

            cda_mermaid_iframe = gr.HTML("")
            cda_mermaid_load_btn.click(
                fn=lambda: "<iframe src='https://mermaid.live/' width='100%' height='600px'></iframe>",
                outputs=cda_mermaid_iframe
            )

            with gr.Accordion("Story Structure Templates", open=False):
                for key, item in mermaidstorystructures.items():
                    with gr.Accordion(key, open=False):
                        gr.Code(item, label=key, language=None)

            with gr.Accordion("Concept Blending Examples", open=False):
                for key, item in examplemermaidconceptblendingstrutures.items():
                    gr.Code(item, label=key, language=None)

        # ==================== D&D 5E SRD REFERENCE TAB ====================
        with gr.Tab("D&D 5e SRD"):
            gr.Markdown("### Dungeons & Dragons 5th Edition - System Reference Document")

            with gr.Accordion("What is D&D 5e?", open=True):
                gr.Markdown("""
**Dungeons & Dragons 5th Edition** is a tabletop role-playing game (TTRPG) published by Wizards of the Coast.

**Core Concepts:**
- **Players** create characters with races (Elf, Dwarf, Human, etc.) and classes (Fighter, Wizard, Rogue, etc.)
- **Dungeon Master (DM)** narrates the story, controls NPCs/monsters, and adjudicates rules
- **Dice-based resolution** - primarily the d20 (20-sided die) for skill checks, attacks, and saves
- **Combat** uses turn-based initiative with movement, actions, and reactions
- **Character progression** through levels 1-20 with increasing abilities and spells

**Why use D&D for game config inspiration?**
- Rich ecosystem of monsters, items, spells, and locations
- Well-balanced mechanics tested over decades
- Familiar framework for many players
- Excellent source for fantasy game content
                """)

            with gr.Accordion("License Information (CC-BY-4.0)", open=False):
                gr.Markdown("""
**System Reference Document 5.1 (SRD 5.1)** is available under **Creative Commons Attribution 4.0 International (CC-BY-4.0)**.

**What this means:**
- โœ… You CAN use SRD 5.1 content in your games (commercial or non-commercial)
- โœ… You CAN modify and adapt the content
- โœ… You CAN share and redistribute
- โš ๏ธ You MUST give appropriate credit to Wizards of the Coast
- โŒ You CANNOT use D&D trademarks (like "Dungeons & Dragons" in your product name)

**Attribution Example:**
> "This work includes material from the System Reference Document 5.1 ("SRD 5.1") by Wizards of the Coast LLC, available at https://dnd.wizards.com/resources/systems-reference-document. The SRD 5.1 is licensed under the Creative Commons Attribution 4.0 International License."

**Official Sources:**
- [SRD 5.1 PDF](https://dnd.wizards.com/resources/systems-reference-document)
- [CC-BY-4.0 License](https://creativecommons.org/licenses/by/4.0/)
                """)

            with gr.Accordion("Random Idea Generator (SRD Content)", open=True):
                gr.Markdown("Generate random D&D elements for game inspiration. All content from SRD 5.1.")

                # SRD Monster list (subset for demo)
                DND_MONSTERS = [
                    "Aboleth", "Animated Armor", "Banshee", "Basilisk", "Behir", "Beholder", "Bugbear",
                    "Bulette", "Centaur", "Chimera", "Cockatrice", "Couatl", "Cyclops", "Death Knight",
                    "Doppelganger", "Dragon (Red)", "Dragon (Gold)", "Dragon (Black)", "Drider", "Dryad",
                    "Duergar", "Elemental (Fire)", "Elemental (Water)", "Elemental (Earth)", "Elemental (Air)",
                    "Ettercap", "Ettin", "Gargoyle", "Genie (Djinni)", "Genie (Efreeti)", "Ghost", "Ghoul",
                    "Giant (Hill)", "Giant (Stone)", "Giant (Frost)", "Giant (Fire)", "Giant (Cloud)", "Giant (Storm)",
                    "Gibbering Mouther", "Gnoll", "Goblin", "Golem (Clay)", "Golem (Stone)", "Golem (Iron)",
                    "Gorgon", "Green Hag", "Griffon", "Harpy", "Hell Hound", "Hippogriff", "Hobgoblin",
                    "Hydra", "Intellect Devourer", "Invisible Stalker", "Kobold", "Kraken", "Lamia", "Lich",
                    "Lizardfolk", "Manticore", "Medusa", "Merfolk", "Mimic", "Mind Flayer", "Minotaur",
                    "Mummy", "Naga (Guardian)", "Nightmare", "Ogre", "Oni", "Orc", "Otyugh", "Owlbear",
                    "Pegasus", "Phase Spider", "Piercer", "Pixie", "Pseudodragon", "Purple Worm", "Rakshasa",
                    "Remorhaz", "Roc", "Roper", "Rust Monster", "Sahuagin", "Salamander", "Satyr",
                    "Shambling Mound", "Shield Guardian", "Skeleton", "Specter", "Sphinx", "Sprite",
                    "Stirge", "Succubus/Incubus", "Tarrasque", "Treant", "Troll", "Unicorn", "Vampire",
                    "Wight", "Will-o'-Wisp", "Wraith", "Wyvern", "Xorn", "Zombie"
                ]

                DND_SPELLS = [
                    "Fireball", "Lightning Bolt", "Magic Missile", "Shield", "Mage Armor", "Detect Magic",
                    "Dispel Magic", "Counterspell", "Fly", "Invisibility", "Polymorph", "Teleport",
                    "Wish", "Power Word Kill", "Meteor Swarm", "Time Stop", "Gate", "True Resurrection",
                    "Heal", "Cure Wounds", "Revivify", "Raise Dead", "Greater Restoration", "Mass Heal",
                    "Bless", "Spirit Guardians", "Guiding Bolt", "Sacred Flame", "Banishment", "Hold Person",
                    "Charm Person", "Suggestion", "Dominate Person", "Fear", "Sleep", "Hypnotic Pattern",
                    "Wall of Fire", "Wall of Force", "Cloudkill", "Cone of Cold", "Chain Lightning",
                    "Disintegrate", "Finger of Death", "Prismatic Spray", "Sunburst", "Earthquake"
                ]

                DND_ITEMS = [
                    "Bag of Holding", "Cloak of Elvenkind", "Boots of Speed", "Ring of Protection",
                    "Wand of Fireballs", "Staff of Power", "Vorpal Sword", "Holy Avenger", "Flame Tongue",
                    "Frost Brand", "Dancing Sword", "Luck Blade", "Rod of Lordly Might", "Sphere of Annihilation",
                    "Deck of Many Things", "Portable Hole", "Immovable Rod", "Rope of Climbing",
                    "Amulet of Proof Against Detection", "Belt of Giant Strength", "Bracers of Defense",
                    "Carpet of Flying", "Crystal Ball", "Eversmoking Bottle", "Figurine of Wondrous Power",
                    "Gauntlets of Ogre Power", "Headband of Intellect", "Helm of Brilliance", "Horn of Blasting",
                    "Ioun Stone", "Lantern of Revealing", "Medallion of Thoughts", "Mirror of Life Trapping",
                    "Necklace of Fireballs", "Periapt of Health", "Robe of Eyes", "Scarab of Protection",
                    "Talisman of Pure Good", "Wings of Flying"
                ]

                DND_CLASSES = [
                    "Barbarian - Primal warriors fueled by rage",
                    "Bard - Magical performers and jack-of-all-trades",
                    "Cleric - Divine spellcasters serving a deity",
                    "Druid - Nature-based spellcasters who shapeshift",
                    "Fighter - Masters of martial combat",
                    "Monk - Martial artists harnessing ki energy",
                    "Paladin - Holy warriors bound by an oath",
                    "Ranger - Wilderness experts and hunters",
                    "Rogue - Stealthy specialists and skill experts",
                    "Sorcerer - Innate magic users with metamagic",
                    "Warlock - Spellcasters with otherworldly patrons",
                    "Wizard - Scholarly magic users with spellbooks"
                ]

                DND_LOCATIONS = [
                    "Ancient Dragon Lair", "Abandoned Dwarven Mine", "Cursed Graveyard", "Floating Castle",
                    "Underground City (Underdark)", "Haunted Manor", "Wizard's Tower", "Sunken Temple",
                    "Frost Giant Stronghold", "Volcanic Forge", "Feywild Glade", "Shadowfell Crossing",
                    "Planar Portal Chamber", "Lich's Phylactery Vault", "Beholder's Lair", "Mind Flayer Colony",
                    "Pirate Cove", "Desert Pyramid", "Jungle Ziggurat", "Arctic Glacier Dungeon"
                ]

                import random

                def generate_dnd_ideas(num_monsters, num_spells, num_items, include_class, include_location):
                    result = []

                    if num_monsters > 0:
                        monsters = random.sample(DND_MONSTERS, min(num_monsters, len(DND_MONSTERS)))
                        result.append(f"**Monsters ({num_monsters}):**\n" + "\n".join(f"โ€ข {m}" for m in monsters))

                    if num_spells > 0:
                        spells = random.sample(DND_SPELLS, min(num_spells, len(DND_SPELLS)))
                        result.append(f"**Spells ({num_spells}):**\n" + "\n".join(f"โ€ข {s}" for s in spells))

                    if num_items > 0:
                        items = random.sample(DND_ITEMS, min(num_items, len(DND_ITEMS)))
                        result.append(f"**Magic Items ({num_items}):**\n" + "\n".join(f"โ€ข {i}" for i in items))

                    if include_class:
                        char_class = random.choice(DND_CLASSES)
                        result.append(f"**Suggested Class:**\nโ€ข {char_class}")

                    if include_location:
                        location = random.choice(DND_LOCATIONS)
                        result.append(f"**Location Idea:**\nโ€ข {location}")

                    return "\n\n".join(result) if result else "Select at least one category!"

                with gr.Row():
                    dnd_num_monsters = gr.Slider(minimum=0, maximum=10, value=3, step=1, label="Number of Monsters")
                    dnd_num_spells = gr.Slider(minimum=0, maximum=10, value=3, step=1, label="Number of Spells")
                    dnd_num_items = gr.Slider(minimum=0, maximum=10, value=2, step=1, label="Number of Magic Items")
                with gr.Row():
                    dnd_include_class = gr.Checkbox(label="Include Random Class", value=True)
                    dnd_include_location = gr.Checkbox(label="Include Random Location", value=True)

                dnd_generate_btn = gr.Button("Generate Random D&D Ideas", variant="primary")
                dnd_output = gr.Markdown(label="Generated Ideas")

                dnd_generate_btn.click(
                    generate_dnd_ideas,
                    inputs=[dnd_num_monsters, dnd_num_spells, dnd_num_items, dnd_include_class, dnd_include_location],
                    outputs=dnd_output
                )

            with gr.Accordion("Quick Reference - Combat Basics", open=False):
                gr.Markdown("""
**Combat Round Structure:**
1. **Roll Initiative** (d20 + Dexterity modifier) - determines turn order
2. **Take Turns** - each creature gets: Movement + Action + Bonus Action (if available)
3. **Repeat** until combat ends

**Action Types:**
- **Attack** - Make a weapon or spell attack
- **Cast a Spell** - Use a spell (some are bonus actions)
- **Dash** - Double your movement
- **Disengage** - Move without provoking opportunity attacks
- **Dodge** - Attacks against you have disadvantage
- **Help** - Give an ally advantage on their next check
- **Hide** - Attempt to become hidden
- **Ready** - Prepare an action for a trigger

**Advantage/Disadvantage:**
- **Advantage** = Roll 2d20, take the higher
- **Disadvantage** = Roll 2d20, take the lower

**For Text Games:** Consider simplifying to choice-based combat with stat checks rather than full dice simulation.
                """)

            with gr.Accordion("SRD Lookup (Open5e API)", open=True):
                gr.Markdown("*Search the full D&D 5e SRD database via Open5e API for detailed monster stats, spell descriptions, and more.*")

                # Random search terms for "I'm Feeling Lucky"
                SRD_RANDOM_SEARCHES = {
                    "monsters": ["dragon", "goblin", "orc", "zombie", "skeleton", "wolf", "giant", "demon", "troll", "ogre", "vampire", "ghost", "spider", "bear", "elemental"],
                    "spells": ["fire", "ice", "lightning", "heal", "shield", "teleport", "invisibility", "charm", "sleep", "detect", "summon", "cure", "protection", "dispel", "light"],
                    "magicitems": ["sword", "ring", "staff", "wand", "cloak", "boots", "belt", "amulet", "potion", "bag", "helm", "gauntlets", "armor", "shield", "rod"]
                }

                def srd_feeling_lucky():
                    """Pick a random category and search term, then search."""
                    import random
                    category = random.choice(["monsters", "spells", "magicitems"])
                    search_term = random.choice(SRD_RANDOM_SEARCHES[category])
                    # Return the category, search term (to update inputs)
                    return category, search_term

                with gr.Row():
                    srd_api_category = gr.Dropdown(
                        label="Category",
                        choices=[
                            ("Monsters", "monsters"),
                            ("Spells", "spells"),
                            ("Magic Items", "magicitems"),
                            ("Conditions", "conditions"),
                            ("Classes", "classes")
                        ],
                        value="monsters"
                    )
                    srd_api_search = gr.Textbox(
                        label="Search",
                        placeholder="goblin, fireball, vorpal...",
                        scale=2
                    )
                    srd_api_lucky_btn = gr.Button("๐ŸŽฒ Lucky", variant="secondary")
                    srd_api_search_btn = gr.Button("Search", variant="primary")

                srd_api_lucky_btn.click(
                    fn=srd_feeling_lucky,
                    outputs=[srd_api_category, srd_api_search]
                )

                srd_api_results = gr.Markdown("*Enter a search term and click Search to query the Open5e API*")

                with gr.Row():
                    srd_api_detail_slug = gr.Textbox(
                        label="Get Full Details (slug)",
                        placeholder="goblin, fireball, vorpal-sword...",
                        info="Enter the item's slug (lowercase, hyphenated name) from search results"
                    )
                    srd_api_detail_btn = gr.Button("Get Full Stats")

                srd_api_detail_output = gr.Markdown("")

                def srd_api_search_handler(category, query):
                    """Handle SRD API search."""
                    if not query.strip():
                        return "Please enter a search term"
                    if category == "monsters":
                        return search_monsters(query)
                    elif category == "spells":
                        return search_spells(query)
                    elif category == "magicitems":
                        return search_magicitems(query)
                    elif category == "conditions":
                        return search_conditions(query)
                    elif category == "classes":
                        return search_classes(query)
                    return "Select a category"

                def srd_api_detail_handler(category, slug):
                    """Handle SRD API detail lookup."""
                    if not slug:
                        return "Enter a slug to get details"
                    slug = slug.lower().strip().replace(" ", "-")
                    if category == "monsters":
                        return get_monster_details(slug)
                    elif category == "spells":
                        return get_spell_details(slug)
                    elif category == "magicitems":
                        return get_magicitem_details(slug)
                    return "Detail view available for Monsters, Spells, and Magic Items"

                srd_api_search_btn.click(
                    fn=srd_api_search_handler,
                    inputs=[srd_api_category, srd_api_search],
                    outputs=[srd_api_results]
                )

                srd_api_detail_btn.click(
                    fn=srd_api_detail_handler,
                    inputs=[srd_api_category, srd_api_detail_slug],
                    outputs=[srd_api_detail_output]
                )

                gr.Markdown("""
---
*Live data from [Open5e API](https://open5e.com/) - search returns up to 10 results. Use slugs (e.g., "ancient-red-dragon") for full stat blocks.*
                """)

        # ==================== STORY ARCHITECT TAB ====================
        create_story_architect_tab()

        # ==================== NARRATIVE ENGINE TAB ====================
        create_narrative_engine_tab()

        # ==================== SOURCE CONTENT TO GAMES TAB ====================
        with gr.Tab("Source Content to Games"):
            gr.Markdown("""## Convert Any Text to Game Configs

**Input Sources:**
- Textbooks / Educational materials โ†’ Interactive learning games
- Memes / Sayings / Quotes โ†’ Decision-based humor games
- Song lyrics / Poetry โ†’ Emotional journey games
- Books / Stories / Scripts โ†’ Narrative adventures

**NLP-Guided Process:**
1. Extract key concepts, themes, characters
2. Identify decision points and consequences
3. Map to location โ†’ state โ†’ choices structure
4. Generate valid JSON config
            """)

            with gr.Accordion("Prompts for Each Source Type", open=True):
                gr.Markdown("""
### Textbook/Educational Material
```
Convert this educational content into a text adventure game config:
[PASTE CONTENT]

Create locations for each major concept. Each location should:
- Have a description explaining the concept
- Offer choices that test understanding
- Include consequences that reinforce correct/incorrect answers
Output as JSON with this structure: {"location": {"state": {"description": "...", "choices": [...]}}}
```

### Song Lyrics/Poetry
```
Transform these lyrics into an emotional journey game:
[PASTE LYRICS]

Each verse = a location. Choices reflect the emotional themes.
The chorus can be a recurring location or state change.
Output as JSON game config.
```

### Meme/Saying/Quote
```
Create a short decision game based on this saying:
[PASTE QUOTE]

The game should explore the meaning through 3-5 choices.
Each choice demonstrates understanding or misunderstanding of the wisdom.
Output as JSON game config.
```

### Book/Story Chapter
```
Convert this story excerpt into an interactive adventure:
[PASTE TEXT]

Identify: characters, locations, key decisions, consequences.
Create branching paths where reader choices affect outcomes.
Output as JSON game config.
```
                """)

        # ==================== GEMMA SCOPE ANALYSIS TAB ====================
        with gr.Tab("Gemma Scope Analysis"):
            gr.Markdown("""## Analyze Prompt Features with Gemma Scope 2

See which internal features activate when generating game configs.
Use this to understand what patterns lead to **interesting** vs **predictable** outputs.
            """)

            gr.HTML('''
                <iframe
                    src="https://kwabshug-testsaegemmascope.hf.space"
                    width="100%"
                    height="700px"
                    style="border: 1px solid #ccc; border-radius: 8px;"
                ></iframe>
            ''')
            gr.Markdown("[Open SAE Analyzer in new tab](https://huggingface.co/spaces/KwabsHug/TestSAEGemmaScope)")

            with gr.Accordion("Understanding Feature IDs", open=False):
                gr.Markdown("""
## Gemma Scope Naming Convention

A feature ID like `gemma-2-2b_12-gemmascope-res-16k_4667` breaks down as:

| Component | Meaning |
|-----------|---------|
| `gemma-2-2b` | The base language model being analyzed |
| `12` | Layer 12 - middle layer where abstract concepts form |
| `gemmascope` | The Gemma Scope SAE project |
| `res` | **Residual stream** - the main "highway" of information |
| `16k` | SAE has 16,384 learned features |
| `4667` | This specific feature's ID |

### What Different Layers Capture

| Layer Range | What It Captures |
|-------------|------------------|
| 0-5 | Basic syntax, token patterns, grammar |
| 6-12 | Concepts, word meanings, simple relationships |
| 13-18 | Abstract reasoning, complex semantics |
| 19-25 | Output formatting, final predictions |

**Layer 12** (default) is good for capturing meaningful concepts without being too low-level or too output-focused.
                """)

            with gr.Accordion("About Gemma Scope 2", open=False):
                gr.Markdown("""
**What is Gemma Scope 2?**
Sparse Autoencoders (SAEs) that decompose model activations into interpretable features.
Think of it as a "microscope" for looking inside the AI model.

**Use Cases for Game Config Development:**
- **Plan interesting configs**: Identify which features lead to creative outputs
- **Plan predictable configs**: Find patterns for reliable/consistent results
- Analyze feature activations for different game mechanics (combat, exploration, dialogue)
- Debug unexpected LLM outputs by seeing which features activated

**How to Use:**
1. Enter a prompt you'd use for game config generation
2. Click "Analyze Features" to see which internal features activate
3. Look up specific features to understand what they represent
4. Compare different prompts to understand what patterns the model uses

**Resources:**
- [Neuronpedia Demo](https://www.neuronpedia.org/gemma-scope-2)
- [Technical Paper](https://storage.googleapis.com/deepmind-media/DeepMind.com/Blog/gemma-scope-2-helping-the-ai-safety-community-deepen-understanding-of-complex-language-model-behavior/Gemma_Scope_2_Technical_Paper.pdf)
- [SAELens Library](https://github.com/jbloomAus/SAELens)
                """)

        # ==================== VIDEOGRAPHER PERSPECTIVE TAB ====================
        # NOTE: T5Gemma2 moved to Media Studio โ†’ Generate tab
        with gr.Tab("Videographer Perspective"):
            gr.Markdown("""## Videographer Perspective for Game Configs

Think about your game config like a **film director** or **cinematographer**.
Video is now a supported media type - use these concepts to enhance storytelling.
            """)

            with gr.Accordion("Shot Types & When to Use Them", open=True):
                gr.Markdown("""
**Establishing Shot** - Wide view showing the environment
- Use for: Location introductions, setting the scene
- Config tip: First state in a new location should have establishing imagery/video

**Close-Up** - Tight focus on face/object
- Use for: Emotional moments, important items, decision points
- Config tip: Key choices or reveals deserve close-up media

**Medium Shot** - Waist-up framing
- Use for: Dialogue, character interactions
- Config tip: Standard conversation states

**Over-the-Shoulder** - Camera behind one character looking at another
- Use for: Conversations, confrontations
- Config tip: States where player is observing/listening to NPCs

**POV (Point of View)** - What the character sees
- Use for: Exploration, discovery, immersion
- Config tip: Investigation states, finding clues

**Dutch Angle** - Tilted camera
- Use for: Unease, disorientation, something wrong
- Config tip: Horror/thriller moments, betrayals
                """)

            with gr.Accordion("Pacing & Rhythm", open=False):
                gr.Markdown("""
**Fast Cutting** - Quick transitions between shots
- Creates: Tension, action, urgency
- Config tip: Short descriptions, many quick choices, time pressure

**Long Takes** - Extended continuous shots
- Creates: Immersion, realism, building tension
- Config tip: Detailed descriptions, fewer choices, let moments breathe

**Montage** - Series of shots showing passage of time/progress
- Creates: Progression, training, travel
- Config tip: Summary states, "time passes" transitions

**Parallel Editing** - Cutting between simultaneous events
- Creates: Suspense, showing cause/effect
- Config tip: State variables tracking multiple storylines
                """)

            with gr.Accordion("Lighting & Mood", open=False):
                gr.Markdown("""
**High Key Lighting** - Bright, even, minimal shadows
- Mood: Happy, safe, comedic, optimistic
- Config tip: Describe bright environments, daylight scenes

**Low Key Lighting** - Dark, strong shadows, contrast
- Mood: Mysterious, dangerous, dramatic, noir
- Config tip: Describe shadows, dim lighting, hidden corners

**Practical Lighting** - Light sources visible in scene
- Mood: Realistic, immersive
- Config tip: Mention candles, lamps, screens as light sources

**Color Temperature**
- Warm (orange/yellow): Comfort, nostalgia, intimacy
- Cool (blue/green): Isolation, technology, unease
- Config tip: Include color descriptions in media prompts
                """)

            with gr.Accordion("Camera Movement Concepts", open=False):
                gr.Markdown("""
**Static Camera** - No movement
- Effect: Stability, observation, documentation
- Config tip: Standard descriptive states

**Pan** - Camera rotates left/right
- Effect: Revealing space, following action
- Config tip: Descriptions that scan across a scene

**Tilt** - Camera rotates up/down
- Effect: Showing scale, power dynamics
- Config tip: Looking up at imposing structures, down at fallen enemies

**Dolly/Tracking** - Camera moves through space
- Effect: Following subject, exploration
- Config tip: Descriptions of moving through corridors, chasing

**Zoom** - Lens adjustment (not camera movement)
- Effect: Focusing attention, psychological shift
- Config tip: Transitioning from wide context to specific detail
                """)

            with gr.Accordion("Video Generation Prompts", open=True):
                gr.Markdown("""
### Prompt Templates for Video Media

**Establishing Shot:**
```
Wide cinematic shot of [LOCATION], [TIME OF DAY], [WEATHER].
Camera slowly pans across [KEY FEATURES]. [LIGHTING DESCRIPTION].
```

**Character Introduction:**
```
Medium shot of [CHARACTER], [CLOTHING/APPEARANCE].
[ACTION/POSE]. [EXPRESSION]. [BACKGROUND ELEMENTS].
```

**Action Sequence:**
```
Dynamic tracking shot following [CHARACTER] as they [ACTION].
Fast-paced movement, [ENVIRONMENT DETAILS]. Urgent atmosphere.
```

**Emotional Moment:**
```
Close-up on [CHARACTER]'s face showing [EMOTION].
Soft lighting, shallow depth of field. [SUBTLE MOVEMENT].
```

**Suspense/Horror:**
```
POV shot moving slowly through [DARK LOCATION].
Minimal lighting, shadows moving. Something glimpsed in periphery.
```
                """)

            with gr.Accordion("Story Structure Through Video Lens", open=False):
                gr.Markdown("""
**Three-Act Structure for Videos:**

**Act 1 - Setup (25%)**
- Establishing shots of world
- Character introductions (medium shots)
- Normal world before conflict

**Act 2 - Confrontation (50%)**
- Increasing close-ups as tension rises
- More dynamic camera movements
- Parallel editing for multiple storylines
- Low key lighting as stakes increase

**Act 3 - Resolution (25%)**
- Climax: Rapid cutting, close-ups, dynamic movement
- Resolution: Return to longer takes, breathing room
- Final shot: Often mirrors opening but transformed

**Apply to Configs:**
- Early locations: Establishing shots, bright lighting
- Middle locations: More variety, building tension
- Late game: Intimate shots, dramatic lighting
- Endings: Reflect the journey visually
                """)

            with gr.Accordion("65 Classic Film Scenarios", open=False):
                gr.Markdown("""
### Frequently Reused Film Scenarios
These scenarios appear across countless films. Use them as templates for game states.

**OPENINGS & INTRODUCTIONS**
1. **Dawn Patrol** - Character wakes up, morning routine reveals personality/situation
2. **The Arrival** - Protagonist enters new location (city, building, world) for first time
3. **In Medias Res** - Opens mid-action, audience catches up
4. **The Funeral** - Character death sets story in motion, mourners gathered
5. **Voiceover Reflection** - Older character narrates past events we're about to see

**TENSION & SUSPENSE**
6. **The Ticking Clock** - Countdown visible/mentioned, deadline approaching
7. **Hiding in Plain Sight** - Character conceals identity among enemies
8. **The Stakeout** - Characters wait and watch from vehicle/building
9. **Parallel Editing Chase** - Cut between pursuer and pursued
10. **The Interrogation** - Character questioned under pressure (police, villain, etc.)
11. **Eavesdropping** - Character overhears crucial conversation
12. **The Setup/Double-Cross** - Trusted ally reveals betrayal
13. **Trapped in Enclosed Space** - Elevator, room, vehicle - no escape
14. **The Hostage Situation** - Loved one held, demands made
15. **Walking Into a Trap** - Audience knows danger character doesn't

**ACTION & CONFLICT**
16. **The Standoff** - Multiple parties aim weapons, no one shoots first
17. **The Bar Fight** - Violence erupts in drinking establishment
18. **Car Chase Through City** - Vehicles weave through traffic, obstacles
19. **Rooftop Confrontation** - Final battle on building top, city below
20. **The Heist Execution** - Plan unfolds step by step (with complications)
21. **Training Montage** - Character improves skills over compressed time
22. **The Last Stand** - Outnumbered defenders hold position
23. **One vs Many** - Single fighter takes on multiple opponents
24. **The Duel** - Two opponents face off, formal or informal
25. **Escape Sequence** - Character flees captivity/danger

**EMOTIONAL MOMENTS**
26. **The Confession** - Character admits truth (love, crime, secret)
27. **Deathbed Scene** - Dying character's final words/wishes
28. **The Reunion** - Long-separated characters meet again
29. **Breaking the News** - Character learns devastating information
30. **The Sacrifice** - Character gives up something precious for others
31. **Saying Goodbye** - Characters part ways, possibly forever
32. **The Breakdown** - Character's composure finally cracks
33. **Reconciliation** - Estranged characters make peace
34. **The Proposal** - Marriage or significant commitment offered
35. **Visiting the Grave** - Character speaks to deceased at burial site

**DISCOVERY & REVELATION**
36. **Finding the Body** - Character discovers corpse
37. **The Evidence Room** - Character finds proof of conspiracy/truth
38. **Flashback Reveal** - Past event recontextualizes everything
39. **The Twist Revealed** - Major plot revelation changes understanding
40. **Reading the Letter/Document** - Written words deliver crucial info
41. **Surveillance Footage** - Character watches recording of key event
42. **The Photograph** - Image reveals connection or identity
43. **Decoding the Message** - Cipher/puzzle solved, meaning clear

**SOCIAL SCENARIOS**
44. **The Dinner Party** - Tension beneath polite social gathering
45. **The Job Interview** - Character proves worth or fails to
46. **Meeting the Parents** - Romantic partner meets family
47. **The Courtroom** - Legal proceedings, testimony, verdict
48. **Press Conference** - Public statement, reporters' questions
49. **The Gala/Ball** - Formal event, everyone dressed up, intrigue beneath
50. **The Wake/Reception** - Social gathering after significant event

**ENDINGS & CONCLUSIONS**
51. **Walking Into the Sunset** - Hero departs, back to camera, horizon ahead
52. **The Circular Return** - Final scene mirrors opening, showing change
53. **Freeze Frame** - Action stops, often with voiceover or text overlay
54. **The Bittersweet Victory** - Won but at great cost, hollow celebration
55. **New Dawn** - Sun rises on changed world/character, hope restored
56. **The Cliffhanger** - Unresolved tension, question left hanging
57. **Where Are They Now** - Text/montage showing characters' futures
58. **The Twist Ending** - Final revelation reframes entire story
59. **Full Circle Reunion** - Characters gather one last time
60. **The Long Walk Away** - Character leaves location, camera lingers
61. **Passing the Torch** - Legacy/knowledge transferred to next generation
62. **The Final Confrontation** - Last face-to-face with antagonist
63. **Quiet Moment After Storm** - Calm after climax, processing events
64. **The Sacrifice Payoff** - Earlier sacrifice proven worthwhile
65. **Open Road/New Beginning** - Character sets off on next journey

---
**Using These in Configs:**
- Each scenario = potential game state template
- Combine scenarios for complex scenes (Dinner Party + The Setup)
- Consider which shot types fit each (Interrogation = close-ups, Chase = tracking)
- Match lighting to mood (Funeral = low key, Gala = high key)
                """)

            with gr.Accordion("Scenario Sequence Generator", open=True):
                gr.Markdown("### Generate Story Sequences from Film Scenarios")
                gr.Markdown("Create 3-10 scene sequences for your game config. Output as list, JSON config, or send prompts to generation queue.")

                with gr.Row():
                    seq_count = gr.Slider(minimum=3, maximum=10, value=5, step=1, label="Number of Scenes")

                with gr.Row():
                    seq_opening = gr.Checkbox(label="Openings", value=True)
                    seq_tension = gr.Checkbox(label="Tension", value=True)
                    seq_action = gr.Checkbox(label="Action", value=True)
                    seq_emotional = gr.Checkbox(label="Emotional", value=True)

                with gr.Row():
                    seq_discovery = gr.Checkbox(label="Discovery", value=True)
                    seq_social = gr.Checkbox(label="Social", value=True)
                    seq_ending = gr.Checkbox(label="Endings", value=True)

                with gr.Row():
                    seq_force_opening = gr.Checkbox(label="Force Opening First", value=True)
                    seq_force_ending = gr.Checkbox(label="Force Ending Last", value=True)

                with gr.Row():
                    seq_media_type = gr.Dropdown(
                        choices=["image", "audio", "3d", "tts"],
                        value="image",
                        label="Media Type",
                        scale=1
                    )
                    seq_auto_queue = gr.Checkbox(label="Auto-add to Queue", value=False, scale=1)
                    seq_generate_btn = gr.Button("Generate Sequence", variant="primary", scale=2)

                with gr.Row():
                    with gr.Column():
                        seq_list_output = gr.Markdown(label="Sequence List")
                    with gr.Column():
                        seq_json_output = gr.Code(label="Config JSON", language="json", lines=15)

                with gr.Row():
                    seq_prompts_output = gr.Textbox(label="Media Prompts (for queue)", lines=8, interactive=False)

                with gr.Row():
                    seq_add_to_queue_btn = gr.Button("Add Prompts to Queue", variant="secondary", scale=2)
                    seq_queue_status = gr.Textbox(label="Status", interactive=False, scale=2)
                    seq_queue_count = gr.Textbox(label="Queue", value="0 items", interactive=False, scale=1)

                def generate_with_optional_queue(count, inc_open, inc_tens, inc_act, inc_emo,
                                                  inc_disc, inc_soc, inc_end, force_open, force_end,
                                                  media_type, auto_queue):
                    """Generate sequence and optionally add to queue."""
                    list_out, json_out, prompts_out = generate_scenario_sequence(
                        count, inc_open, inc_tens, inc_act, inc_emo,
                        inc_disc, inc_soc, inc_end, force_open, force_end
                    )

                    if auto_queue and prompts_out:
                        _, queue_info, status = add_scenario_prompts_to_queue(prompts_out, media_type)
                        return list_out, json_out, prompts_out, status, queue_info
                    else:
                        return list_out, json_out, prompts_out, "", f"{len(generation_queue)} items"

                seq_generate_btn.click(
                    generate_with_optional_queue,
                    inputs=[seq_count, seq_opening, seq_tension, seq_action, seq_emotional,
                            seq_discovery, seq_social, seq_ending, seq_force_opening, seq_force_ending,
                            seq_media_type, seq_auto_queue],
                    outputs=[seq_list_output, seq_json_output, seq_prompts_output, seq_queue_status, seq_queue_count]
                )

                def add_prompts_with_type(prompts_text, media_type):
                    """Add prompts to queue with specified media type."""
                    _, queue_info, status = add_scenario_prompts_to_queue(prompts_text, media_type)
                    return status, queue_info

                seq_add_to_queue_btn.click(
                    add_prompts_with_type,
                    inputs=[seq_prompts_output, seq_media_type],
                    outputs=[seq_queue_status, seq_queue_count]
                )

    with gr.Tab("Portability & Design"):
        with gr.Tab("Platform Export"):
            gr.Markdown("### Export to Game Engines")
            gr.Markdown("Select a platform, paste your game config JSON, then click Export.")

            # Platform test info - shows where to test selected platform
            PLATFORM_TEST_INFO = {
                "playcanvas": ("PlayCanvas Editor", "https://playcanvas.com/", "Paste JavaScript into a new script component"),
                "godot": ("GDScript Online", "https://gdscript-online.github.io/", "Test GDScript snippets online, or use Godot Editor"),
                "unreal": ("Unreal Engine", "https://www.unrealengine.com/", "Requires Unreal Engine 5.x with Python scripting enabled"),
                "gamemaker": ("GameMaker", "https://gamemaker.io/", "Create new project, add script resource"),
                "flutter": ("DartPad", "https://dartpad.dev/", "Paste Dart code to test UI logic"),
                "twine": ("Twinery.org", "https://twinery.org/", "Import HTML or paste into new story"),
                "renpy": ("Ren'Py", "https://www.renpy.org/", "Download SDK, replace script.rpy"),
                "ink": ("Inky Editor", "https://www.inklestudios.com/ink/", "Download Inky or use web playground"),
                "yarn": ("Try Yarn Spinner", "https://try.yarnspinner.dev/", "Paste .yarn code and click Run"),
                "roblox": ("Roblox Studio", "https://www.roblox.com/create", "Create ModuleScript in ReplicatedStorage"),
                "rpgmaker": ("RPG Maker MZ", "https://www.rpgmakerweb.com/", "Save as js/plugins/StoryAdventure.js"),
                "minecraft": ("Minecraft Java", "https://www.minecraft.net/", "Create datapack in world/datapacks folder"),
                "papyrus": ("Creation Kit", "https://www.creationkit.com/", "Compile .psc with Papyrus compiler"),
                "vrchat": ("VRChat SDK", "https://hello.vrchat.com/", "Unity 2019.4 + VRChat SDK3 + UdonSharp"),
                "lensstudio": ("Lens Studio", "https://lensstudio.snapchat.com/", "Free download, create new lens project"),
                "metaspark": ("Meta Spark Studio", "https://spark.meta.com/", "Free download, create AR effect"),
                "8thwall": ("8th Wall", "https://www.8thwall.com/", "WebAR - works in mobile browser"),
                "tiktok": ("Effect House", "https://effecthouse.tiktok.com/", "Free download, create TikTok effect"),
                "reality": ("Xcode", "https://developer.apple.com/xcode/", "Requires Xcode 15+ for visionOS/iOS"),
                "inform7": ("Inform 7 / Borogove", "https://borogove.app/", "Online IDE or download Inform 7"),
                "godot_dialogue": ("Godot + Dialogue Manager", "https://github.com/nathanhoad/godot_dialogue_manager", "Install addon from AssetLib"),
                "movingdotspace": ("Browser", "", "Self-contained HTML - open in any browser, use arrow keys"),
                "terminal": ("Python", "https://replit.com/", "Run with 'python game.py' - works on Replit, Pydroid, any Python env"),
                "existing game": ("Various", "", "JSON format for manual conversion to your target"),
            }

            def get_platform_info(platform):
                """Get test info for selected platform."""
                if not platform or platform == "":
                    return ""
                info = PLATFORM_TEST_INFO.get(platform, ("Unknown", "", ""))
                name, url, tip = info
                if url:
                    return f"**Test at:** [{name}]({url})  \n**Tip:** {tip}"
                elif name:
                    return f"**Test at:** {name}  \n**Tip:** {tip}"
                return ""

            platform_info_display = gr.Markdown(
                value=get_platform_info("playcanvas"),
                elem_classes=["platform-info-box"]
            )

            # Platform dropdown with all options grouped
            platform_choices = [
                ("โ”€โ”€ Game Engines โ”€โ”€", ""),
                ("PlayCanvas", "playcanvas"),
                ("Godot 4.x", "godot"),
                ("Unreal 5.x", "unreal"),
                ("GameMaker", "gamemaker"),
                ("Flutter", "flutter"),
                ("โ”€โ”€ Narrative Engines โ”€โ”€", ""),
                ("Twine", "twine"),
                ("Ren'Py", "renpy"),
                ("Ink", "ink"),
                ("Yarn Spinner", "yarn"),
                ("โ”€โ”€ Game Platforms โ”€โ”€", ""),
                ("Roblox", "roblox"),
                ("RPG Maker MZ", "rpgmaker"),
                ("Minecraft", "minecraft"),
                ("Skyrim/Fallout (Papyrus)", "papyrus"),
                ("VRChat", "vrchat"),
                ("โ”€โ”€ AR/XR Platforms โ”€โ”€", ""),
                ("Lens Studio", "lensstudio"),
                ("Meta Spark", "metaspark"),
                ("8th Wall", "8thwall"),
                ("TikTok Effect House", "tiktok"),
                ("Apple Reality", "reality"),
                ("โ”€โ”€ Interactive Fiction โ”€โ”€", ""),
                ("Inform 7", "inform7"),
                ("Godot Dialogue Manager", "godot_dialogue"),
                ("โ”€โ”€ Playable HTML โ”€โ”€", ""),
                ("MovingDotSpace", "movingdotspace"),
                ("โ”€โ”€ Terminal โ”€โ”€", ""),
                ("Python Terminal Game", "terminal"),
                ("Existing Game (JSON)", "existing game"),
            ]

            with gr.Row():
                platform_selector = gr.Dropdown(
                    choices=platform_choices,
                    value="playcanvas",
                    label="Target Platform",
                    scale=2
                )
                export_btn = gr.Button("Export", variant="primary", scale=1)
                export_zip_btn = gr.Button("Download ZIP", variant="secondary", scale=1)

            with gr.Row():
                config_input_export = gr.Textbox(label="Paste Game Config JSON", lines=6, placeholder='{"village": {"start": {"description": "...", "choices": [...]}}}', scale=4)
                load_sandwich_btn = gr.Button("๐Ÿ“ฅ Load Sandwich Quest Demo", scale=1)

            # Load sandwich quest demo
            def load_sandwich_demo():
                try:
                    import os
                    demo_path = os.path.join(os.path.dirname(__file__), "sandwich_quest_demo.json")
                    with open(demo_path, 'r', encoding='utf-8') as f:
                        return f.read()
                except Exception as e:
                    return f'{{"error": "Could not load demo: {str(e)}"}}'

            load_sandwich_btn.click(fn=load_sandwich_demo, outputs=[config_input_export])

            # Update platform info when selection changes
            platform_selector.change(
                fn=get_platform_info,
                inputs=[platform_selector],
                outputs=[platform_info_display]
            )

            with gr.Row():
                export_explanation = gr.Textbox(label="Instructions", lines=8, interactive=False)
                export_code = gr.Code(label="Generated Code", language="javascript")

            # ZIP download components
            with gr.Row():
                export_zip_file = gr.File(label="Download ZIP", interactive=False)
                export_zip_status = gr.Textbox(label="ZIP Status", interactive=False, lines=2)

            export_btn.click(
                fn=ConfigConversionforExporttoPlatform,
                inputs=[platform_selector, config_input_export],
                outputs=[export_explanation, export_code]
            )

            # ZIP export function
            def export_platform_as_zip(platform, config_json):
                """Export platform code as a ZIP file."""
                if not config_json or not config_json.strip():
                    return None, "No config provided"

                try:
                    import tempfile
                    import zipfile
                    from datetime import datetime

                    # Get the export output
                    explanation, code = ConfigConversionforExporttoPlatform(platform, config_json)

                    if not code:
                        return None, "Export failed - no code generated"

                    timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
                    zip_filename = f"{platform}_export_{timestamp}.zip"
                    zip_path = os.path.join(tempfile.gettempdir(), zip_filename)

                    with zipfile.ZipFile(zip_path, 'w', zipfile.ZIP_DEFLATED) as zipf:
                        # Add setup instructions
                        zipf.writestr("README_SETUP.txt", explanation)

                        # Add code file(s) based on platform
                        if platform == "godot":
                            # Godot outputs multiple files separated by markers
                            # Parse the combined output into separate files
                            files = parse_godot_output(code)
                            for filename, content in files.items():
                                zipf.writestr(filename, content)
                        elif platform == "playcanvas":
                            zipf.writestr("game.js", code)
                        elif platform == "unreal":
                            zipf.writestr("game_controller.py", code)
                        elif platform == "gamemaker":
                            zipf.writestr("game_controller.gml", code)
                        elif platform == "flutter":
                            zipf.writestr("main.dart", code)
                        elif platform == "twine":
                            zipf.writestr("story.html", code)
                        elif platform == "renpy":
                            zipf.writestr("script.rpy", code)
                        elif platform == "ink":
                            zipf.writestr("story.ink", code)
                        elif platform == "yarn":
                            zipf.writestr("dialogue.yarn", code)
                        elif platform == "roblox":
                            zipf.writestr("StoryModule.lua", code)
                        elif platform == "rpgmaker":
                            zipf.writestr("js/plugins/StoryAdventure.js", code)
                        elif platform == "lensstudio":
                            zipf.writestr("StoryExperience.js", code)
                        elif platform == "metaspark":
                            zipf.writestr("StoryEffect.js", code)
                        elif platform == "8thwall":
                            zipf.writestr("index.html", code)
                        elif platform == "minecraft":
                            zipf.writestr("datapack_instructions.txt", code)
                        elif platform == "papyrus":
                            zipf.writestr("StoryAdventure.psc", code)
                        elif platform == "vrchat":
                            zipf.writestr("StoryAdventure.cs", code)
                        elif platform == "tiktok":
                            zipf.writestr("StoryEffect.js", code)
                        elif platform == "reality":
                            zipf.writestr("StoryView.swift", code)
                        elif platform == "inform7":
                            zipf.writestr("story.ni", code)
                        elif platform == "godot_dialogue":
                            zipf.writestr("story.dialogue", code)
                        elif platform == "movingdotspace" or platform == "2d map related space":
                            zipf.writestr("game.html", code)
                        elif platform == "terminal":
                            zipf.writestr("game.py", code)
                        else:
                            zipf.writestr("export.txt", code)

                        # Add the original config
                        zipf.writestr("config.json", config_json)

                    return zip_path, f"Exported: {zip_filename}"
                except Exception as e:
                    return None, f"ZIP error: {str(e)}"

            def parse_godot_output(combined_code):
                """Parse Godot's combined output into separate files."""
                files = {}
                current_file = None
                current_content = []

                for line in combined_code.split('\n'):
                    # Check for file markers like "# === game_state.gd ===" or "### FILE: game_state.gd ###"
                    if line.startswith('# ===') and '===' in line[5:]:
                        if current_file and current_content:
                            files[current_file] = '\n'.join(current_content)
                        # Extract filename
                        filename = line.replace('# ===', '').replace('===', '').strip()
                        current_file = filename
                        current_content = []
                    elif line.startswith('### FILE:') and '###' in line[9:]:
                        if current_file and current_content:
                            files[current_file] = '\n'.join(current_content)
                        filename = line.replace('### FILE:', '').replace('###', '').strip()
                        current_file = filename
                        current_content = []
                    else:
                        current_content.append(line)

                # Don't forget the last file
                if current_file and current_content:
                    files[current_file] = '\n'.join(current_content)

                # If no files were parsed, return as single file
                if not files:
                    files["export.gd"] = combined_code

                return files

            export_zip_btn.click(
                fn=export_platform_as_zip,
                inputs=[platform_selector, config_input_export],
                outputs=[export_zip_file, export_zip_status]
            )

            gr.Markdown("""
| Engine | Status | Output | Test Online |
|--------|--------|--------|-------------|
| **Game Engines** ||||
| PlayCanvas | Ready | JavaScript | [PlayCanvas Editor](https://playcanvas.com/) |
| Godot 4.x | Ready | .tscn + GDScript (ZIP) | [GDScript Online](https://gdscript-online.github.io/) |
| Unreal 5.x | Ready | Python script | Desktop only |
| GameMaker | Ready | GML script | [GameMaker](https://gamemaker.io/) |
| Flutter | Ready | Dart code | [DartPad](https://dartpad.dev/) |
| **Narrative Engines** ||||
| Twine | Ready | HTML story | [Twinery.org](https://twinery.org/) |
| Ren'Py | Ready | .rpy script | [Ren'Py](https://www.renpy.org/) |
| Ink | Ready | .ink story | [Inky Editor](https://www.inklestudios.com/ink/) |
| Yarn Spinner | Ready | .yarn dialogue | [Try Yarn](https://try.yarnspinner.dev/) |
| **Game Platforms** ||||
| Roblox | Ready | Lua ModuleScript | [Roblox Studio](https://www.roblox.com/create) |
| RPG Maker MZ | Ready | .js plugin | [RPG Maker](https://www.rpgmakerweb.com/) |
| Minecraft | Ready | Datapack (mcfunction) | In-game testing |
| Skyrim/Fallout | Ready | Papyrus .psc | [Creation Kit](https://www.creationkit.com/) |
| VRChat | Ready | UdonSharp .cs | [VRChat SDK](https://hello.vrchat.com/) |
| **AR/XR Platforms** ||||
| Lens Studio | Ready | JavaScript | [Lens Studio](https://lensstudio.snapchat.com/) |
| Meta Spark | Ready | JavaScript | [Meta Spark](https://spark.meta.com/) |
| 8th Wall | Ready | HTML + A-Frame | [8th Wall](https://www.8thwall.com/) |
| TikTok Effect House | Ready | JavaScript | [Effect House](https://effecthouse.tiktok.com/) |
| Apple Reality | Ready | Swift/RealityKit | [Xcode](https://developer.apple.com/xcode/) |
| **Interactive Fiction** ||||
| Inform 7 | Ready | Natural language | [Inform 7](http://inform7.com/) |
| Godot Dialogue | Ready | .dialogue file | [Dialogue Manager](https://github.com/nathanhoad/godot_dialogue_manager) |
| **Playable HTML** ||||
| MovingDotSpace | Ready | Self-contained HTML | Browser (arrow keys + modals) |
| **Terminal** ||||
| Python Terminal | Ready | Python script | [Replit](https://replit.com/) / Pydroid / Any Python |
            """)

        create_mechanic_translation_tab()

        with gr.Tab("Theory & Expansion Ideas"):
            # with gr.Row():
            #     with gr.Column():
            with gr.Accordion("'1d' vs 2d vs 3d", open=False):
                gr.Markdown("""**Test your config in different dimensions:**
- **1D (Text):** Test tab โ†’ Playtest & Edit
- **2D (Top-down):** Test tab โ†’ Game Preview (2D) (MovingDotSpace)
- **3D (WebGL):** Test tab โ†’ Game Preview (3D) (PlayCanvas)

---

# Suggestions from Llama 405b through Lambdachat

To create 2D and 3D versions of your 1D text-based game, you'll need to expand your game engine to support additional features. Here's a high-level overview of the steps you can follow:

1. For 2D (top-down traversal):

a. Create a grid-based system: Instead of just having a linear sequence of decisions, create a 2D grid that represents the game world. Each cell in the grid can represent a location in the game world, and the player can move between adjacent cells.

b. Implement movement: Allow the player to move in four directions (up, down, left, right) by updating their position on the grid. You can use input commands like "go north", "go south", "go east", and "go west".

c. Add obstacles and interactive objects: Place obstacles (e.g., walls, locked doors) and interactive objects (e.g., keys, items) on the grid. The player will need to navigate around obstacles and interact with objects to progress in the game.

d. Update game logic: Modify your game's logic to account for the player's position on the grid and any interactions with objects or NPCs.

2. For 3D:

a. Add a third dimension: Expand your 2D grid to a 3D grid by adding a new dimension (e.g., height). This will allow you to create multi-level environments with stairs, elevators, or other vertical traversal methods.

b. Implement movement in 3D: Extend your movement system to allow the player to move up and down in addition to the four cardinal directions. You can use input commands like "go up" and "go down".

c. Update game logic for 3D: Modify your game's logic to account for the player's position in 3D space, as well as any interactions with objects or NPCs that may occur at different heights.

d. Add 3D-specific features: Consider adding features that take advantage of the 3D environment, such as jumping, falling, or flying.

In both cases, you'll need to update your game's user interface to accommodate the additional dimensions. This may involve displaying a top-down view of the game world, rendering a 3D environment, or providing additional text descriptions to convey the player's surroundings.

Keep in mind that creating 2D and 3D games will require more complex programming and design compared to a 1D text-based game. You may need to learn new programming concepts and tools to achieve your goals.

                        
# More ideas for expansion of '1d' ideas
                        
Expanding a 1D text-based game into 2D and 3D versions can introduce various new gameplay elements and features. Here are 10 additional points for each expansion, assuming we can debug and code any idea we want:

2D Expansion:

1. Add a mini-map: Implement a mini-map feature that displays the player's current position and the surrounding area, making navigation more intuitive.

2. Introduce NPCs with movement: Create non-player characters (NPCs) that can move around the grid, adding life to the game world and offering new interaction opportunities.

3. Develop a dialogue system: Design a dialogue system that allows players to engage in conversations with NPCs, further enriching the game's narrative.

4. Implement a day-night cycle: Add a day-night cycle that affects gameplay, such as certain events or NPCs only being available during specific times.

5. Design puzzles: Create grid-based puzzles that players must solve to progress in the game, such as pushing blocks to activate switches or navigating mazes.

6. Add character customization: Allow players to customize their character's appearance and attributes, giving them a sense of ownership over their avatar.

7. Introduce a crafting system: Implement a crafting system that enables players to combine items found in the game world to create new, more powerful items.

8. Add weather effects: Introduce weather effects like rain, snow, or fog that can impact gameplay, such as reducing visibility or making certain areas inaccessible.

9. Create a quest system: Design a quest system with various objectives for players to complete, providing a sense of progression and purpose.

10. Develop a party system: Allow players to recruit NPCs to join their party, assisting them in combat and providing unique abilities.

3D Expansion:

1. Add camera controls: Implement camera controls that allow players to rotate and zoom their view of the 3D game world, providing greater flexibility in exploration.

2. Introduce platforming elements: Add platforming elements like jumping, climbing, and ledge-grabbing to enhance traversal in the 3D environment.

3. Develop a physics system: Create a physics system that governs object interactions, enabling realistic behaviors like collisions, gravity, and buoyancy.

4. Implement destructible environments: Design destructible environments that react to player actions, such as breaking walls or collapsing structures.

5. Add aerial gameplay: Introduce flying mounts or vehicles that allow players to explore the game world from the air, opening up new traversal possibilities.

6. Create underwater sections: Design underwater areas with unique gameplay mechanics, such as swimming, diving, and underwater combat.

7. Introduce mounted combat: Allow players to engage in combat while riding mounts, adding a new strategic layer to battles.

8. Develop a dynamic weather system: Create a dynamic weather system that affects gameplay in real-time, such as strong winds impacting movement or lightning strikes causing damage.

9. Implement a stealth system: Design a stealth system that enables players to avoid detection by enemies, using cover, distractions, and silent takedowns.

10. Add virtual reality support: Implement virtual reality support, allowing players to fully immerse themselves in the 3D game world using VR headsets and motion controls.

Remember that these ideas can be mixed and matched to create unique gameplay experiences tailored to your vision for the game.
                        
# More ideas for '1d' game idea
                        
1D text-based games have their own unique strengths and limitations. Here are some ideas that can be best explored or are exclusive to 1D text-based games:

1. Focus on narrative: 1D text-based games can focus primarily on storytelling, allowing for rich, branching narratives without the need for complex graphics or animations.

2. Emphasize imagination: With no visual elements, 1D text-based games rely on the player's imagination to visualize the game world, making the experience more personal and engaging.

3. Develop complex dialogue trees: In a 1D text-based game, you can create intricate dialogue trees with multiple choices and consequences, allowing for deep character interactions.

4. Create puzzles based on text manipulation: Design puzzles that involve manipulating or deciphering text, such as riddles, word scrambles, or cipher-based challenges.

5. Implement a text-based inventory system: Create an inventory system that relies on text descriptions of items, allowing players to use their imagination to determine how to use or combine objects.

6. Explore experimental storytelling techniques: 1D text-based games can experiment with unconventional narrative structures, such as non-linear storytelling, interactive fiction, or second-person narration.

7. Focus on resource management: Implement resource management mechanics that rely on text descriptions, such as managing a character's hunger, thirst, or fatigue levels.

8. Develop a text-based skill tree: Create a skill tree system that uses text descriptions to convey character progression and abilities, allowing players to make meaningful choices about their character's development.

9. Create a text-based AI companion: Design an AI companion that communicates with the player through text, offering guidance, hints, or engaging in conversations.

10. Emphasize accessibility: 1D text-based games can be more accessible to players with visual impairments, as they can be played using screen readers or other assistive technologies.

While some of these ideas can be adapted to 2D and 3D games, they are particularly well-suited for 1D text-based games, where the focus is on narrative, imagination, and text-driven gameplay.
                                    
        """)
            # with gr.Column():
            gr.HTML("Main idea for this tab is ways to reuse the config in same/different way in other platforms - Need a conversion management interface")
            gr.HTML("Side Quests can be to build with a real world 3D printer - eg. Map or speculating how uncharted territories are")
            with gr.Accordion("Basic planning for conversions", open=False):
                gr.Markdown("**Use the Platform Export tool in the 'Platform Export' tab above for actual conversion.**")
                gr.HTML("MikeTheTech Tutorials (He has many more playlists so check the rest of his channel) - <br>playcanvas https://www.youtube.com/playlist?list=PLJKGfra8Jl0B845PNo9cMxAQfghJrYH1Y, <br>unreal engine - https://www.youtube.com/watch?v=STHdIdWO0tk&list=PLJKGfra8Jl0CSjCzk1r0peTp0orIleqdG, <br>gamemaker - https://www.youtube.com/watch?v=ka_fVrGMOwo&list=PLJKGfra8Jl0AW3rNuwcmi_aq_PdsjQtbu ")
            gr.HTML("Reskinng and extending the Tutorials / smallest examples = fastest way to gain intuition for whats important")
            gr.HTML("For 3D with regard to this space - see '3D Study and Tutorials' โ†’ '3D Background with UI' tab")
            with gr.Tab("Twine - Open-source"):
                gr.Markdown("### Twine Export")
                gr.HTML("<a href='https://twinery.org/' target='_blank'>twinery.org</a> - Story based games | Twee File = easy import | Local Install = Actual Save Files instead of local storage in browser")

                with gr.Row():
                    twine_config_input = gr.Textbox(
                        label="Game Config JSON",
                        lines=8,
                        placeholder='{"village": {"start": {"description": "You arrive at the village.", "choices": ["Enter tavern", "Talk to guard"], "transitions": {"Enter tavern": "tavern", "Talk to guard": "guard"}}}}',
                        scale=3
                    )
                    with gr.Column(scale=1):
                        twine_load_demo_btn = gr.Button("๐Ÿ“ฅ Load Demo Config", variant="secondary")
                        twine_export_btn = gr.Button("๐ŸŽฎ Export to Twine", variant="primary")

                twine_output = gr.Code(label="Twine/Twee Output", language="html", lines=12)
                twine_status = gr.Markdown("")

                def load_twine_demo():
                    try:
                        import os
                        demo_path = os.path.join(os.path.dirname(__file__), "sandwich_quest_demo.json")
                        with open(demo_path, 'r', encoding='utf-8') as f:
                            return f.read()
                    except Exception as e:
                        return f'{{"error": "Could not load demo: {str(e)}"}}'

                def export_to_twine_ui(config_json):
                    if not config_json or not config_json.strip():
                        return "", "โš ๏ธ Please provide a game config JSON"
                    try:
                        from exporters import export_to_twine
                        explanation, code = export_to_twine(config_json)
                        if code:
                            return code, f"โœ… Twine export generated!\n\n{explanation}"
                        else:
                            return "", f"โŒ Export failed: {explanation}"
                    except Exception as e:
                        return "", f"โŒ Error: {str(e)}"

                twine_load_demo_btn.click(fn=load_twine_demo, outputs=[twine_config_input])
                twine_export_btn.click(
                    fn=export_to_twine_ui,
                    inputs=[twine_config_input],
                    outputs=[twine_output, twine_status]
                )

                with gr.Accordion("Example Twine/Twee File Structure", open=False):
                    gr.Code(ExampleTwineFileStructureasInitialPrompt, language="html")
            with gr.Tab("3D Engine Resources"):
                gr.Markdown("""### 3D Game Engine Export Resources
Use the **Platform Export** tab to generate code, then use these resources to build your 3D game.
                """)
                with gr.Accordion("PlayCanvas", open=True):
                    gr.Markdown("""**Select 'playcanvas' in Platform Export to generate JavaScript code.**

Generated code includes: GameState, ConditionEvaluator, EffectApplicator, TransitionResolver, scene entities, and click handling.

**Live Preview:** Use the **Game Preview (3D)** tab for interactive 3D preview.
                    """)
                    with gr.Accordion("UI in PlayCanvas", open=False):
                        gr.HTML("Basic - Add 2 Entities to the root of the hierachy (Left top - displays items in the scene) - <br>one will load the story script and the will hold the UI items and load the UI script (Both Below) <br> UI entitiy needs to have a screen and script items added under its properties (left hand side) <br>UI Entity also needs three items added to it. text (need a font as well to load), a container for buttons, and the button that gets turned into a template (hierachy menu options)")
                        with gr.Column():
                            gr.Code(playcanvasstorymanager)
                            gr.Code(playcanvasuimanager)
                    with gr.Accordion("Tutorials & Resources", open=False):
                        gr.HTML("Playcanvas Tutorials - https://developer.playcanvas.com/tutorials/webxr-hello-world/, Wow - https://developer.playcanvas.com/user-manual/assets/types/wasm/  <br>https://github.com/playcanvas/playcanvas.github.io - https://playcanvas.vercel.app/#/misc/hello-world ")
                        gr.HTML("""
                        https://playcanvas.vercel.app/#/physics/vehicle
                        https://forum.playcanvas.com/t/assets-free-3d-models-sprites-icons-and-sounds-for-your-games/19199
                        https://github.com/playcanvas/playcanvas.github.io/tree/main
                        https://github.com/playcanvas/engine
                        https://github.com/playcanvas/engine/blob/main/examples/src/examples/physics/vehicle.example.mjs
                        https://github.com/playcanvas/engine/blob/main/examples/src/examples/misc/editor.example.mjs
                        https://github.com/playcanvas/engine/blob/main/examples/src/examples/input/keyboard.example.mjs
                        https://github.com/playcanvas/engine/blob/main/examples/src/examples/input/mouse.example.mjs
                        https://github.com/playcanvas/engine/blob/main/examples/src/examples/camera/first-person.example.mjs
                        """)
                        gr.HTML("https://youtu.be/a3pJiZ86XgA (Learn.Nimagin) - Youtube video showing user interface in playcanvas")
                    with gr.Accordion("Notes", open=False):
                        gr.HTML("How can add 100 shapes in playcanvas very quickly? - Seems one at a time during editor phase")
                        gr.HTML("Each location is new scene?")
                        gr.HTML("Repurpose the ball demo - ball replaced with a custom 3D object <br> platform can used as map floor by changing dimensions, islands unlock = hidden platforms unhidden by a trigger (verticality as location access control) <br>Teleport can be loader for UI ")
                with gr.Accordion("Godot 4.x", open=False):
                    gr.Markdown("""**Select 'godot' in Platform Export to generate GDScript + Scene files.**

Generated files:
- `main.tscn` - Scene with all locations and choices
- `game_state.gd` - AutoLoad singleton (add in Project Settings)
- `game_controller.gd` - Navigation and state management
- `condition_evaluator.gd`, `effect_applicator.gd`, `transition_resolver.gd`
- `choice.gd` - Script for clickable choice boxes

**Setup:** Add `game_state.gd` as AutoLoad named "GameState" in Project Settings.
                    """)
                    with gr.Accordion("Tutorials & Resources", open=False):
                        gr.HTML("Godot Docs - https://docs.godotengine.org/en/stable/")
                        gr.HTML("GDQuest - https://www.gdquest.com/")
                        gr.HTML("https://github.com/godotengine/godot-demo-projects")
                with gr.Accordion("Unreal Engine 5", open=False):
                    gr.Markdown("""**Select 'unreal' in Platform Export to generate a Python script.**

**Requirements:** Enable "Python Editor Script Plugin" in Edit -> Plugins

**Usage:**
1. Open Python Console: Window -> Developer Tools -> Output Log
2. Paste the generated script
3. Run `start_game()` to create the scene
4. Use `list_choices()` and `select_choice('id')` to play

Note: This is for prototyping in-editor. For a shipped game, convert to Blueprints.
                    """)
                    with gr.Accordion("Tutorials & Resources", open=False):
                        gr.HTML("Learning Centre - https://dev.epicgames.com/community/unreal-engine/learning")
                        gr.HTML("Python in Unreal - https://docs.unrealengine.com/5.0/en-US/scripting-the-unreal-editor-using-python/")
                with gr.Accordion("Existing Games as Engines", open=False):
                    gr.HTML("Unreal Engine for Fortnite https://dev.epicgames.com/community/fortnite/getting-started/uefn")
                    gr.HTML("https://www.reddit.com/r/singularity/comments/1fd4oo1/roblox_announces_ai_tool_for_generating_3d_game/ - roblox and genai")
                    gr.HTML("Modding Tools? eg. Skyrim, GTA, sims 4 custom scenarios")
                    gr.HTML("GTA (Rockstar Editor) - UI or mission next objective system")
                    gr.HTML("SIMS - Buildings as Paths - Like a maze path is your decisions")
                    gr.HTML("Racing Game - Next turn = choice")
                    gr.HTML("Other games as Iframes and MLM as the judge (visual confirmation) aka the quest completion algorithm")

        with gr.Tab("AR/XR Integration (Future)"):
            gr.Markdown("""## AR/XR Integration Notes

**Full AR/XR documentation has been moved to a dedicated section.**

For comprehensive AR/XR resources including:
- Platform comparison tables (Lens Studio, Meta Spark, Effect House, Adobe Aero, 8th Wall)
- File types, export formats, and testing devices
- Detailed workflows for each platform
- Integration ideas for game configs
- WebXR and browser-based AR
- Publishing and distribution guides
- Animation resources (Mixamo alternatives)

**See: 3D Study and Tutorials โ†’ AR/XR Development tab**

This keeps AR/XR content consolidated with other 3D resources for easier reference.
            """)

            gr.Markdown("---")
            gr.Markdown("*Navigate to '3D Study and Tutorials' โ†’ 'AR/XR Development' for full documentation.*")

    # NOTE: "Leveraging Machine Learning" tab has been merged into "Media Studio" (ui_gr_media_management.py)
    # All content preserved in: Media Studio โ†’ Generate โ†’ Local (ZeroGPU), API, Resources

    # NOTE: Resources Hub tab moved inside Mini-Tutorial & Resources accordion (testgroupingUIremotely)

    # 3D Study tab (extracted to ui_tabs/study_3d_tab.py)
    create_3d_study_tab()

    # Story Graph and Big RPG Scale moved to Config Development Assistance tab

demo.queue().launch(share=True)