File size: 33,503 Bytes
e2c29ae
 
 
 
 
 
38a477f
4aecbd9
 
883d90b
4aecbd9
 
 
 
38a477f
e2c29ae
38a477f
e2c29ae
 
38a477f
 
86f9b29
 
 
 
 
 
 
 
 
 
 
 
38a477f
86f9b29
38a477f
 
 
966cf22
38a477f
966cf22
4aecbd9
 
 
38a477f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
966cf22
38a477f
e2c29ae
 
883d90b
 
 
 
 
 
ccf617f
883d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2c29ae
38a477f
 
966cf22
38a477f
 
 
c18cb5f
 
966cf22
c18cb5f
966cf22
38a477f
c18cb5f
 
38a477f
c18cb5f
883d90b
38a477f
 
e2c29ae
 
38a477f
 
 
 
 
 
 
 
 
3ece12e
 
883d90b
 
38a477f
e2c29ae
 
 
 
 
 
38a477f
e2c29ae
38a477f
e2c29ae
38a477f
e2c29ae
38a477f
 
 
e2c29ae
 
38a477f
 
 
e2c29ae
 
 
 
 
38a477f
e2c29ae
38a477f
e2c29ae
38a477f
e2c29ae
38a477f
 
 
966cf22
 
 
 
 
 
 
38a477f
966cf22
38a477f
966cf22
38a477f
966cf22
c18cb5f
 
38a477f
 
c18cb5f
38a477f
 
c18cb5f
4aecbd9
c18cb5f
38a477f
 
c18cb5f
38a477f
 
c18cb5f
38a477f
 
 
 
 
 
 
 
 
 
c18cb5f
966cf22
 
c18cb5f
38a477f
 
 
c18cb5f
ccf617f
c18cb5f
 
966cf22
 
38a477f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2c29ae
38a477f
e2c29ae
 
38a477f
 
090a127
883d90b
e2c29ae
38a477f
e2c29ae
38a477f
 
e2c29ae
3ece12e
 
 
883d90b
 
 
38a477f
 
 
 
 
3ece12e
 
 
38a477f
 
883d90b
 
38a477f
 
 
883d90b
38a477f
 
 
e2c29ae
3ece12e
883d90b
38a477f
 
 
883d90b
 
 
 
 
 
 
 
 
 
 
 
38a477f
3ece12e
38a477f
883d90b
 
38a477f
 
883d90b
 
38a477f
883d90b
38a477f
 
e2c29ae
 
38a477f
883d90b
38a477f
 
 
e2c29ae
38a477f
 
e2c29ae
 
 
 
 
 
38a477f
e2c29ae
38a477f
e2c29ae
 
 
966cf22
 
 
c18cb5f
e2c29ae
 
 
 
ccf617f
 
e2c29ae
883d90b
3ece12e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2c29ae
c18cb5f
966cf22
38a477f
 
883d90b
e2c29ae
 
 
 
38a477f
883d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e2c29ae
 
38a477f
e2c29ae
883d90b
 
 
 
 
 
 
 
 
 
 
e2c29ae
 
883d90b
966cf22
 
 
 
883d90b
 
 
e2c29ae
 
3ece12e
090a127
 
 
e2c29ae
c18cb5f
966cf22
c18cb5f
966cf22
 
c18cb5f
966cf22
 
 
 
c18cb5f
 
e2c29ae
966cf22
e2c29ae
c18cb5f
966cf22
38a477f
966cf22
 
 
 
38a477f
966cf22
 
 
 
 
c18cb5f
 
966cf22
 
 
 
 
 
 
 
 
 
38a477f
966cf22
c18cb5f
966cf22
38a477f
966cf22
e2c29ae
966cf22
 
e2c29ae
 
 
c18cb5f
e2c29ae
c18cb5f
 
 
883d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c18cb5f
 
38a477f
 
883d90b
 
 
 
 
38a477f
883d90b
 
 
 
 
 
 
 
 
 
 
 
 
38a477f
883d90b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38a477f
c18cb5f
 
 
38a477f
883d90b
 
 
 
966cf22
c18cb5f
 
 
38a477f
883d90b
38a477f
c18cb5f
966cf22
e2c29ae
c18cb5f
38a477f
 
 
c18cb5f
966cf22
c18cb5f
966cf22
38a477f
966cf22
38a477f
966cf22
 
 
 
c18cb5f
 
966cf22
c18cb5f
 
 
966cf22
 
c18cb5f
e2c29ae
 
c18cb5f
 
966cf22
 
c18cb5f
 
883d90b
e2c29ae
 
3ece12e
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
import gradio as gr
import json
import os
from dotenv import load_dotenv
from datetime import datetime

from engine import (
    RPGEngine,
    generate_full_setup,
    generate_from_image_setup,
    generate_character_from_prompt,
    stream_literary_chapter,
    GENRE_CHOICES,
    DEFAULT_GENRE,
)

load_dotenv()
OPENROUTER_API_KEY = os.getenv("OPENROUTER_KEY", "")

# --- UI LOGIC FORMATTERS ---

def format_output(steps, max_steps=8):
    """
    Render the simulation history into Markdown for display.
    Only the last `max_steps` entries are shown to keep the UI responsive,
    especially on mobile devices.
    """
    if not steps: 
        return "Simulation results will appear here..."

    # Only show the last `max_steps` steps to avoid huge Markdown blocks
    visible_steps = steps[-max_steps:]
    # Numbering is relative to the visible window (1..max_steps)
    output = []  
    for i, step in enumerate(visible_steps, 1):  
        if step.get("error"):  
            output.append(f"\n❌ **Step {i}: Error**\n> {step['error']}")  
            continue  
            
        stype = step.get("type", "character_action")
        
        if stype == "gm_opening":
            output.append(f"\n{'='*60}\n🎲 **Step {i} | OPENING SCENE**\n\n{step.get('gm_narration', '')}")
        elif stype == "system_reflection":
            output.append(f"\n{'='*60}\nπŸ”„ **Step {i} | SYSTEM REFLECTION**\n> {step.get('gm_narration')}")
        elif stype == "gm_directed":
            output.append(f"\n{'='*60}\n⚑ **Step {i} | GM / DIRECTOR EVENT**\n> {step.get('gm_narration')}")
        elif stype == "player_action":
            output.append(f"\n{'='*60}\nπŸ§‘ **Step {i} | PLAYER ACTION**\n> {step.get('gm_narration')}")
        elif stype == "world_event":
            output.append(f"\n{'='*60}\n🌍 **Step {i} | WORLD EVENT**\n> {step.get('gm_narration')}")
        else:
            name = step.get('character_name', '???')  
            thinking = step.get('thinking', '')  
            action = step.get('action', '')  
            speech = step.get('speech', '')  
            gm_narration = step.get('gm_narration', '')  
            world_state = step.get('world_state', '')  
              
            block = [f"\n{'='*60}", f"πŸ”Ή **Step {i}** | 🎭 Actor: `{name}`"]  
            if thinking: block.append(f"πŸ’­ _Thinking_: _{thinking}_")  
            if action: block.append(f"🎬 _Attempting_: *{action}*")  
            if speech: block.append(f"πŸ’¬ **Speech**: \"{speech}\"")  
            if gm_narration: block.append(f"\n🎲 **Game Master (GM)**: {gm_narration}")  
            if world_state: block.append(f"🌍 _Hidden World State_: _{world_state}_")  
            output.append("\n".join(block))  
            
    return "\n".join(output)

def update_preview(char_list):
    if not char_list: 
        return "<div style='color: gray; padding: 10px;'>πŸ”Ή Character list is empty. Add at least one!</div>", gr.update(choices=[], value=None)
    
    html = "<div style='display: flex; flex-direction: column; gap: 10px; max-height: 400px; overflow-y: auto; padding-right: 5px;'>"
    choices = []
    for i, c in enumerate(char_list):
        name = c.get('name', f'Character {i+1}')
        core = str(c.get('core_identity', '')).replace('\n', '<br>')
        pers = str(c.get('personality', '')).replace('\n', '<br>')
        agd = str(c.get('agenda', '')).replace('\n', '<br>')
        inv = str(c.get('inventory', '')).replace('\n', '<br>')
        rel = str(c.get('relationships', '')).replace('\n', '<br>')
        
        card = f'''
        <details style='border: 1px solid #ddd; border-radius: 8px; padding: 10px; background: rgba(128,128,128,0.05);'>
            <summary style='font-weight: bold; cursor: pointer; font-size: 1.1em; user-select: none;'>{i+1}. {name}</summary>
            <div style='margin-top: 10px; font-size: 0.95em; line-height: 1.5; padding-left: 10px; border-left: 3px solid #666;'>
                <p><b>🧬 Core Identity:</b> {core}</p>
                <p><b>🎭 Personality/Mood:</b> {pers}</p>
                <p><b>🎯 Agenda:</b> {agd}</p>
                <p><b>πŸŽ’ Inventory:</b> {inv}</p>
                <p><b>🀝 Relationships:</b> {rel}</p>
            </div>
        </details>
        '''
        html += card
        choices.append(f"{i}: {name}")
    html += "</div>"
    
    return html, gr.update(choices=choices)

def update_dynamic_ui(engine):
    if not engine:
        return gr.update(), gr.update(), gr.update(), gr.update()
    
    agent_names = engine.agent_names
    ws = engine.world_state
    
    return (
        gr.update(choices=["[Auto GM Choice]"] + agent_names, value="[Auto GM Choice]"),
        gr.update(choices=agent_names, value=agent_names[0] if agent_names else None),
        gr.update(value=ws),
        gr.update(choices=agent_names, value=agent_names[0] if agent_names else None)
    )

# --- ENGINE WRAPPERS FOR GRADIO ---

def start_engine_ui(world_setting, public_lore, char_list, model, api_key, gm_vibe, custom_vibe_instr, story_arc, steps, memory_len, reflection_int, use_jailbreak):
    if not api_key.strip() or not world_setting.strip() or not char_list or len(char_list) < 1: 
        yield "❌ Input missing", "", None, gr.update(interactive=False), gr.update(interactive=False)
        return

    clean_chars = [c for c in char_list if c.get('name', '').strip()]  
    engine = RPGEngine(
        world_setting=world_setting, 
        public_lore=public_lore, 
        agents=clean_chars, 
        model_name=model, 
        api_key=api_key, 
        gm_vibe=gm_vibe, 
        memory_length=memory_len, 
        reflection_interval=reflection_int,
        custom_vibe_instructions=custom_vibe_instr,
        story_arc=story_arc,
        use_jailbreak=use_jailbreak
    )  
    
    current_actor = ""
    for is_final, data, actor_name in engine.run_steps_generator(steps):
        current_actor = actor_name
        if not is_final:
            live_text = format_output(engine.history) + "\n\n" + data
            yield f"⏳ Running... ({actor_name})", live_text, engine, gr.update(), gr.update()
        else:
            yield f"⏳ Finished step. Next: {actor_name}", format_output(engine.history), engine, gr.update(), gr.update()
            
    yield f"βœ… Paused. Next: {current_actor}", format_output(engine.history), engine, gr.update(interactive=True), gr.update(interactive=True)

def continue_engine_ui(engine, add_steps, force_actor_name):
    if not engine: 
        yield "❌ Start simulation first", "", engine, gr.update(), gr.update()
        return
    
    if force_actor_name and force_actor_name != "[Auto GM Choice]" and force_actor_name in engine.agent_names:
        engine.current_actor_idx = engine.agent_names.index(force_actor_name)

    current_actor = ""
    for is_final, step_data, actor_name in engine.run_steps_generator(add_steps):
        current_actor = actor_name
        if not is_final:
            live_text = format_output(engine.history) + "\n\n" + step_data
            yield f"⏳ Continuing... ({actor_name})", live_text, engine, gr.update(), gr.update()
        else:
            yield f"⏳ Finished step. Next: {actor_name}", format_output(engine.history), engine, gr.update(), gr.update()
    
    yield f"βœ… Paused. Next: {current_actor}", format_output(engine.history), engine, gr.update(interactive=True), gr.update(interactive=True)

def run_directed_event_ui(engine, instruction):
    if not engine or not instruction.strip():
        yield "❌ Invalid input", "", engine, gr.update(), gr.update()
        return
        
    current_actor = ""
    for is_final, step_data, actor_name in engine.run_directed_event_generator(instruction):
        current_actor = actor_name
        if not is_final:
            live_text = format_output(engine.history) + "\n\n" + step_data
            yield f"⏳ Executing Director's Event...", live_text, engine, gr.update(), gr.update()
        else:
            yield f"⏳ Finished event. Next: {actor_name}", format_output(engine.history), engine, gr.update(), gr.update()

    yield f"βœ… Event Completed. Next: {current_actor}", format_output(engine.history), engine, gr.update(interactive=True), gr.update(interactive=True)

# --- MID-GAME EDITING FUNCTIONS ---

def undo_last_step(engine):
    if not engine or not engine.history: return "❌ Session/History empty", gr.update(), engine
    
    popped_step = engine.history.pop()
    stype = popped_step.get("type", "")
    
    if stype not in ["system_reflection", "gm_directed", "gm_opening", "player_action", "world_event"]:
        char_name = popped_step.get("character_name")
        if char_name in engine.agent_names:
            engine.current_actor_idx = engine.agent_names.index(char_name)
            
    engine.world_state = engine.history[-1].get("world_state", engine.world_setting) if engine.history else engine.world_setting
    engine.steps_since_reflection = max(0, engine.steps_since_reflection - 1)
    
    return f"βͺ Undo successful.", format_output(engine.history), engine

def update_world_state_manual(engine, new_state):
    if not engine: return "❌ Start simulation first", engine
    engine.world_state = new_state.strip()
    return "βœ… World State Overwritten", engine

def load_active_character_info(engine, char_name):
    if not engine or not char_name: return "", "", "", "", ""
    for a in engine.agents:
        if a["name"] == char_name:
            return a.get("core_identity", ""), a.get("personality", ""), a.get("agenda", ""), a.get("inventory", ""), a.get("relationships", "")
    return "", "", "", "", ""

def save_active_character_info(engine, char_name, new_core, new_pers, new_agenda, new_inv, new_rel):
    if not engine or not char_name: return "❌ Error", engine
    for a in engine.agents:
        if a["name"] == char_name:
            a["core_identity"] = new_core
            a["personality"] = new_pers
            a["agenda"] = new_agenda
            a["inventory"] = new_inv
            a["relationships"] = new_rel
            return f"βœ… {char_name} updated!", engine
    return "❌ Character not found", engine

def set_secret_whisper(engine, char_name, whisper_text):
    if not engine or not char_name: return "❌ Error", engine
    engine.whispers[char_name] = whisper_text.strip()
    return f"βœ… Whisper set for {char_name}.", engine

def inject_player_action(engine, action_text):
    if not engine or not action_text.strip(): return "❌ Error", gr.update(), engine
    step_data = {"type": "player_action", "gm_narration": f"*{action_text.strip()}*", "world_state": engine.world_state}
    engine.history.append(step_data)
    return f"βœ… Action Injected", format_output(engine.history), engine

def inject_world_event(engine, event_text):
    if not engine or not event_text.strip(): return "❌ Error", gr.update(), engine
    engine.world_state += f" SUDDEN EVENT: {event_text.strip()}"
    step_data = {"type": "world_event", "gm_narration": f"⚠️ **World Event**: {event_text.strip()}", "world_state": engine.world_state}
    engine.history.append(step_data)
    return f"βœ… Injected Event", format_output(engine.history), engine

# --- I/O EXPORT/IMPORT ---

def export_session(engine):
    if not engine: return None
    filename = f"rpg_log_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
    with open(filename, "w", encoding="utf-8") as f: json.dump(engine.to_dict(), f, ensure_ascii=False, indent=2)
    return filename

def load_session(file_obj, api_key):
    if not file_obj:
        return (None, "❌ No file selected", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
                gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update())
    try:
        with open(file_obj.name, "r", encoding="utf-8") as f: data = json.load(f)
        
        # Hydrate object directly
        engine = RPGEngine.from_dict(data, api_key)
        
        # Normalize gm_vibe: support old str format and new list format
        raw_vibe = engine.gm_vibe
        vibe_value = raw_vibe if isinstance(raw_vibe, list) else ([raw_vibe] if raw_vibe else ["Neutral Realism"])
        
        p_html, p_drop = update_preview(engine.agents)
        
        return (
            engine,
            "βœ… Save loaded successfully!",
            gr.update(value=engine.world_setting),
            gr.update(value=engine.public_lore),
            gr.update(value=vibe_value),
            gr.update(value=engine.custom_vibe_instructions),
            gr.update(value=getattr(engine, 'story_arc', '')),
            gr.update(value=engine.model_name),
            engine.agents,
            p_html,
            p_drop,
            format_output(engine.history),
            gr.update(value=engine.memory_length),
            gr.update(value=engine.reflection_interval),
            gr.update(value=getattr(engine, 'use_jailbreak', False)),
            gr.update(interactive=True),
            gr.update(interactive=True)
        )
    except Exception as e:
        return (None, f"❌ Load error: {str(e)}", gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(),
                gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update(), gr.update())

# --- GENERATORS WRAPPERS ---

def gen_full_wrapper(prompt, genre, api_key, model, current_chars, gm_vibe, use_jailbreak):
    w_set, w_lore, new_chars, status = generate_full_setup(prompt, genre, api_key, model, gm_vibe=gm_vibe, use_jailbreak=use_jailbreak)
    combined = (current_chars or []) + new_chars
    return w_set, w_lore, combined, status, status

def gen_img_wrapper(img_files, extra_instr, genre, api_key, current_chars, gm_vibe, use_jailbreak, img_model):
    if not img_files:
        return "", "", current_chars or [], "❌ No images uploaded", "❌ No images uploaded"
        
    paths = [f.name if hasattr(f, "name") else f["name"] if isinstance(f, dict) else f for f in img_files]
    w_set, w_lore, new_chars, status = generate_from_image_setup(paths, extra_instr, genre, api_key, model=img_model, gm_vibe=gm_vibe, use_jailbreak=use_jailbreak)
    
    combined = (current_chars or []) + new_chars
    return w_set, w_lore, combined, status, status

def gen_char_wrapper(prompt, api_key, model, current_chars, use_jailbreak):
    char, status = generate_character_from_prompt(prompt, api_key, model, use_jailbreak=use_jailbreak)
    if char:
        combined = (current_chars or []) + [char]
        return combined, status
    return current_chars, status

def stream_chapter_wrapper(engine, api_key, model, use_jailbreak):
    if not engine:
        yield "❌ No active session.", gr.update(visible=False)
        return
        
    story_content = ""
    for chunk in stream_literary_chapter(engine.history, api_key, model, use_jailbreak=use_jailbreak):
        story_content = chunk
        yield story_content, gr.update(visible=False)
        
    filename = f"rpg_story_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
    with open(filename, "w", encoding="utf-8") as f: f.write(story_content)
    yield story_content, gr.update(value=filename, visible=True)

# --- MAIN UI BLOCK ---

with gr.Blocks(title="🎲 AI RPG Engine", theme=gr.themes.Soft()) as demo:
    gr.Markdown("# 🎲 AI RPG Engine\n_Multi-agent simulation orchestrated by an AI Game Master_")  
      
    # NOW WE STORE THE ACTUAL RPGEngine INSTANCE!
    session_state = gr.State(None)   
    characters_state = gr.State([])   
      
    with gr.Tabs():  
        with gr.TabItem("βš™οΈ Setup"):  
            with gr.Accordion("πŸ“‚ Load Session", open=False):
                load_file = gr.File(label="Upload JSON History File", file_types=[".json"])
                load_status = gr.Textbox(label="Load Status", interactive=False)

            with gr.Row():  
                with gr.Column(scale=2):  
                    with gr.Group():  
                        gr.Markdown("#### 🌍 World Configuration")  
                        world_setting = gr.Textbox(label="GM Secrets & Initial Situation", lines=3, value="The abandoned space station 'Icarus'. The airlock is jammed intentionally by a traitor.")  
                        public_lore = gr.Textbox(label="Public Lore & Genre Rules", lines=3, value="Sci-Fi horror. Everyone knows they have 2 hours of oxygen left. Characters should act paranoid.")  
                    with gr.Row():
                        model = gr.Dropdown(label="πŸ€– Model", choices=["deepseek/deepseek-v3.2", "meta-llama/llama-3.3-70b-instruct:free", "openrouter/hunter-alpha", "arcee-ai/trinity-large-preview:free"], value="deepseek/deepseek-v3.2", allow_custom_value=True)  
                    gm_vibe = gr.CheckboxGroup(
                        label="🎭 GM Vibe (select one or more)",
                        choices=[
                            "Neutral Realism", "Gritty Survival", "Slice of Life", "Fluffy Romance",
                            "Comedy", "Dark Comedy", "Psychological Horror", "Epic High Drama",
                            "Cozy Mystery", "Action Adventure", "Political Intrigue",
                            "Mythic Folklore", "Philosophical Slow Burn",
                            "── ❀️‍πŸ”₯ Adult / NSFW ──",
                            "Sensual Intimacy", "Slow Burn to Explicit", "Explicit NSFW",
                            "Dominant & Submissive", "Rough & Primal", "Forbidden Desire",
                            "Monster Romance", "Harem Dynamics"
                        ],
                        value=["Gritty Survival"]
                    )
                    custom_vibe_instr = gr.Textbox(label="✍️ Custom Vibe Instructions (optional)", lines=2, placeholder="Add your own instructions to complement the selected vibe, e.g.: 'Use lots of sarcasm' or 'Write in a Victorian style'")
                    story_arc = gr.Textbox(label="🎯 Global Story Arc Goal (optional)", lines=2, placeholder="e.g. 'The traitor must be exposed before the station loses power' β€” GM will steer the narrative toward this goal.")
                    api_key = gr.Textbox(label="πŸ”‘ OpenRouter Key", type="password", value=OPENROUTER_API_KEY)  
                    
                    with gr.Accordion("βš™οΈ Engine Settings", open=False):
                        memory_length = gr.Slider(5, 100, value=30, step=5, label="🧠 Memory Depth (Turns)")
                        reflection_interval = gr.Slider(2, 20, value=5, step=1, label="πŸ”„ System Reflection Interval")
                        use_jailbreak = gr.Checkbox(label="πŸ”“ Enable Jailbreak (Bypass Filters)", value=False)
                  
                with gr.Column(scale=1):  
                    gr.Markdown("### πŸ‘₯ Characters")  
                    with gr.Group():  
                        gr.Markdown("#### 🌍 Quick Generate World & Cast")
                        with gr.Tabs():
                            with gr.TabItem("πŸ“ Text Prompt"):
                                gen_setting_genre = gr.Dropdown(
                                    label="Setting Genre Template",
                                    choices=GENRE_CHOICES,
                                    value=DEFAULT_GENRE,
                                )
                                full_prompt = gr.Textbox(label="Idea / Scenario", lines=2, placeholder="A normal house party...")  
                                btn_gen_full = gr.Button("🎬 Generate World & Cast from Text", variant="primary", size="sm")  
                                full_status = gr.Textbox(label="Status", interactive=False)  
                            
                            with gr.TabItem("πŸ–ΌοΈ Image Prompt"):
                                img_upload = gr.File(label="Upload Image(s)", file_types=["image"], file_count="multiple")
                                img_model = gr.Dropdown(
                                    label="πŸ€– Image Model",
                                    choices=["moonshotai/kimi-k2.5", "openrouter/healer-alpha"],
                                    value="moonshotai/kimi-k2.5",
                                    allow_custom_value=True
                                )
                                img_genre = gr.Dropdown(
                                    label="Setting Genre Template",
                                    choices=GENRE_CHOICES,
                                    value=DEFAULT_GENRE,
                                )
                                extra_instr = gr.Textbox(label="Additional Instructions (context, specific requests)", lines=2, placeholder="There's a hidden monster in the shadows.")
                                btn_gen_img = gr.Button("πŸ–ΌοΈ Generate World & Cast from Image(s)", variant="primary", size="sm")
                                img_status = gr.Textbox(label="Status", interactive=False)
                    with gr.Group():  
                        char_prompt = gr.Textbox(label="Add character by description", lines=1)  
                        btn_gen_char = gr.Button("✨ Generate Character", variant="secondary", size="sm")  
                    with gr.Group():  
                        gr.Markdown("#### ✏️ Character Roster")  
                        with gr.Row():
                            btn_add = gr.Button("βž• Add Empty Character", size="sm")  
                        
                        char_preview = gr.HTML("<div style='color: gray; padding: 10px;'>πŸ”Ή Character list is empty</div>")  

                    with gr.Group():  
                        gr.Markdown("#### ✏️ Character Editor")  
                        with gr.Row():
                            edit_select = gr.Dropdown(label="Select Character to Edit / Remove", choices=[], scale=3)
                            btn_remove = gr.Button("πŸ—‘οΈ Remove Selected", size="sm", scale=1, variant="stop")
                        with gr.Row():  
                            edit_name = gr.Textbox(label="Name", scale=2)  
                        edit_core = gr.Textbox(label="🧬 Core Identity", lines=2)
                        edit_pers = gr.Textbox(label="🎭 Personality/Mood", lines=1)  
                        edit_agenda = gr.Textbox(label="🎯 Agenda", lines=1)  
                        edit_inv = gr.Textbox(label="πŸŽ’ Inventory", lines=1)  
                        edit_rel = gr.Textbox(label="🀝 Relationships", lines=1)  
                        with gr.Row():
                            btn_update = gr.Button("πŸ’Ύ Save Character Changes", variant="primary")  
                            edit_status = gr.Markdown("")  

            with gr.Row():  
                steps_init = gr.Slider(1, 50, value=3, step=1, label="πŸ”’ Steps to start")  
                btn_start = gr.Button("πŸš€ Start RPG Simulation", variant="primary", scale=1)  
            status = gr.Textbox(label="πŸ“Š Status", interactive=False)  

        with gr.TabItem("🎬 Story (Log)"):  
            with gr.Group():
                gr.Markdown("### πŸ•ΉοΈ Control Panel")
                with gr.Row():  
                    steps_cont = gr.Slider(1, 50, value=2, step=1, label="βž• Turns to Generate")  
                    force_actor = gr.Dropdown(label="🎯 Force Next Actor", choices=["[Auto GM Choice]"], value="[Auto GM Choice]")
                with gr.Row():
                    btn_cont = gr.Button("▢️ Continue", variant="primary", interactive=False)  
                    btn_stop = gr.Button("πŸ›‘ Stop", variant="stop")
                    btn_undo = gr.Button("βͺ Undo Last Turn")
                    btn_exp = gr.Button("πŸ“₯ Download JSON", interactive=False)  

            output_md = gr.Markdown("_Waiting for simulation to start..._")  
            
            gr.Markdown("### πŸ”§ Mid-Game Injections & Director Tools")
            with gr.Row():
                with gr.Column():
                    with gr.Accordion("🎬 Directed GM Event (Director Mode)", open=False):
                        dir_instruction = gr.Textbox(label="Director's Instruction", lines=2)
                        btn_dir_event = gr.Button("Trigger Directed Event", variant="primary")

                    with gr.Accordion("🀫 Secret Whisper (To Character)", open=False):
                        whisper_char = gr.Dropdown(label="Target Character")
                        whisper_text = gr.Textbox(label="Secret Whisper", lines=2)
                        btn_set_whisper = gr.Button("Set Whisper", variant="secondary")

                    with gr.Accordion("🌍 World State Editor", open=False):
                        world_state_edit = gr.Textbox(label="Current World State", lines=3)
                        btn_update_ws = gr.Button("πŸ’Ύ Force Update State", variant="secondary")

                with gr.Column():
                    with gr.Accordion("🎭 Active Character Editor", open=False):
                        active_char_dropdown = gr.Dropdown(label="Select Character")
                        active_char_core = gr.Textbox(label="🧬 Core Identity", lines=1)
                        active_char_pers = gr.Textbox(label="🎭 Personality", lines=1)
                        active_char_agenda = gr.Textbox(label="🎯 Agenda", lines=1)
                        active_char_inv = gr.Textbox(label="πŸŽ’ Inventory", lines=1)
                        active_char_rel = gr.Textbox(label="🀝 Relationships", lines=1)
                        btn_update_active_char = gr.Button("πŸ’Ύ Save Character Changes", variant="secondary")

                    with gr.Accordion("πŸ§‘ Player Action Injection", open=False):
                        inj_player = gr.Textbox(label="External/Player Action", lines=2)
                        btn_inject_player = gr.Button("Inject Action", variant="secondary")
                        
                    with gr.Accordion("⚑ Simple World Event Injection", open=False):
                        inj_event = gr.Textbox(label="Event Description", lines=2)
                        btn_inject_event = gr.Button("Inject Event", variant="secondary")
                
            with gr.Accordion("πŸ“– Generate Book Chapter", open=False):
                btn_story = gr.Button("✨ Generate Chapter", variant="primary")
                story_output = gr.Markdown("_Your story will appear here..._")
                story_file = gr.File(label="Download Chapter", visible=False)

            file_out = gr.File(label="JSON Log Download", visible=False)  

    # --- UI LOGIC BINDINGS ---  
    
    # Setup Generators
    btn_gen_full.click(
        gen_full_wrapper, 
        inputs=[full_prompt, gen_setting_genre, api_key, model, characters_state, gm_vibe, use_jailbreak], 
        outputs=[world_setting, public_lore, characters_state, full_status, full_status]
    ).then(update_preview, inputs=[characters_state], outputs=[char_preview, edit_select])  
    
    btn_gen_img.click(
        gen_img_wrapper,
        inputs=[img_upload, extra_instr, img_genre, api_key, characters_state, gm_vibe, use_jailbreak, img_model],
        outputs=[world_setting, public_lore, characters_state, img_status, img_status]
    ).then(update_preview, inputs=[characters_state], outputs=[char_preview, edit_select])
    
    btn_gen_char.click(
        gen_char_wrapper, 
        inputs=[char_prompt, api_key, model, characters_state, use_jailbreak], 
        outputs=[characters_state, full_status]
    ).then(update_preview, inputs=[characters_state], outputs=[char_preview, edit_select])  
    
    # Character List Management
    def add_char(cl):
        cl = cl or []
        new_cl = cl + [{"name": f"Character {len(cl) + 1}", "core_identity": "", "personality": "", "agenda": "", "inventory": "", "relationships": ""}]
        p_html, p_drop = update_preview(new_cl)
        return new_cl, p_html, p_drop

    btn_add.click(add_char, inputs=[characters_state], outputs=[characters_state, char_preview, edit_select])  
    
    def rem_char(cl, selected_str):
        if not selected_str or not cl: 
            p_html, p_drop = update_preview(cl)
            return cl, p_html, p_drop
        try:
            idx = int(selected_str.split(":")[0])
            new_cl = cl[:idx] + cl[idx+1:]
        except:
            new_cl = cl
        p_html, p_drop = update_preview(new_cl)
        return new_cl, p_html, p_drop
        
    btn_remove.click(rem_char, inputs=[characters_state, edit_select], outputs=[characters_state, char_preview, edit_select])  
    
    def load_edit_data(cl, selected_str):
        if not selected_str or not cl:
            return "", "", "", "", "", "", ""
        try:
            idx = int(selected_str.split(":")[0])
            c = cl[idx]
            return c.get('name',''), c.get('core_identity',''), c.get('personality',''), c.get('agenda',''), c.get('inventory',''), c.get('relationships',''), ""
        except:
            return "", "", "", "", "", "", ""

    edit_select.change(load_edit_data, inputs=[characters_state, edit_select], outputs=[edit_name, edit_core, edit_pers, edit_agenda, edit_inv, edit_rel, edit_status])
    
    def apply_edit(cl, selected_str, name, core, pers, agenda, inv, rel):  
        if cl and selected_str:
            try:
                idx = int(selected_str.split(":")[0])
                cl[idx].update({"name": name, "core_identity": core, "personality": pers, "agenda": agenda, "inventory": inv, "relationships": rel})
                p_html, p_drop = update_preview(cl)
                p_drop["value"] = f"{idx}: {name}"
                return cl, p_html, p_drop, "βœ… Character Updated!"
            except:
                pass
        p_html, p_drop = update_preview(cl)
        return cl, p_html, p_drop, ""
        
    btn_update.click(apply_edit, inputs=[characters_state, edit_select, edit_name, edit_core, edit_pers, edit_agenda, edit_inv, edit_rel], outputs=[characters_state, char_preview, edit_select, edit_status])  
    
    # Load Session
    load_file.upload(
        load_session, 
        inputs=[load_file, api_key], 
        outputs=[
            session_state, load_status, world_setting, public_lore, gm_vibe, custom_vibe_instr, 
            story_arc, model, characters_state, char_preview, edit_select, output_md, memory_length, reflection_interval, use_jailbreak, btn_cont, btn_exp
        ]
    ).then(update_dynamic_ui, inputs=[session_state], outputs=[force_actor, active_char_dropdown, world_state_edit, whisper_char])

    # Core Engine Start & Continue
    start_event = btn_start.click(
        start_engine_ui, 
        inputs=[world_setting, public_lore, characters_state, model, api_key, gm_vibe, custom_vibe_instr, story_arc, steps_init, memory_length, reflection_interval, use_jailbreak], 
        outputs=[status, output_md, session_state, btn_cont, btn_exp]
    )
    start_event.then(update_dynamic_ui, inputs=[session_state], outputs=[force_actor, active_char_dropdown, world_state_edit, whisper_char])
    
    cont_event = btn_cont.click(
        continue_engine_ui, 
        inputs=[session_state, steps_cont, force_actor], 
        outputs=[status, output_md, session_state, btn_cont, btn_exp]
    )
    cont_event.then(update_dynamic_ui, inputs=[session_state], outputs=[force_actor, active_char_dropdown, world_state_edit, whisper_char])
    
    dir_event = btn_dir_event.click(
        run_directed_event_ui,
        inputs=[session_state, dir_instruction],
        outputs=[status, output_md, session_state, btn_cont, btn_exp]
    )
    dir_event.then(update_dynamic_ui, inputs=[session_state], outputs=[force_actor, active_char_dropdown, world_state_edit, whisper_char])

    btn_stop.click(fn=None, inputs=None, outputs=None, cancels=[start_event, cont_event, dir_event])

    # Undo Logic
    btn_undo.click(undo_last_step, inputs=[session_state], outputs=[status, output_md, session_state]).then(update_dynamic_ui, inputs=[session_state], outputs=[force_actor, active_char_dropdown, world_state_edit, whisper_char])

    btn_exp.click(export_session, inputs=[session_state], outputs=[file_out]).then(lambda: gr.update(visible=True), outputs=[file_out])
    
    # Injections & Whispers
    btn_set_whisper.click(set_secret_whisper, inputs=[session_state, whisper_char, whisper_text], outputs=[status, session_state])
    btn_inject_player.click(inject_player_action, inputs=[session_state, inj_player], outputs=[status, output_md, session_state])
    btn_inject_event.click(inject_world_event, inputs=[session_state, inj_event], outputs=[status, output_md, session_state])
    
    # Mid-game editors
    btn_update_ws.click(update_world_state_manual, inputs=[session_state, world_state_edit], outputs=[status, session_state])
    active_char_dropdown.change(load_active_character_info, inputs=[session_state, active_char_dropdown], outputs=[active_char_core, active_char_pers, active_char_agenda, active_char_inv, active_char_rel])
    btn_update_active_char.click(save_active_character_info, inputs=[session_state, active_char_dropdown, active_char_core, active_char_pers, active_char_agenda, active_char_inv, active_char_rel], outputs=[status, session_state])

    # Story Gen
    btn_story.click(stream_chapter_wrapper, inputs=[session_state, api_key, model, use_jailbreak], outputs=[story_output, story_file])

if __name__ == "__main__":
    demo.launch()