File size: 52,250 Bytes
c305d1d
41c1a97
a49252c
f6aef7a
 
319aad8
f6aef7a
 
 
 
 
 
 
c305d1d
f6aef7a
 
 
 
c305d1d
 
c6b8a39
f6aef7a
 
c305d1d
 
 
d3f55a0
11a0038
f6aef7a
 
 
 
d3f55a0
c305d1d
f6aef7a
 
d3f55a0
c305d1d
 
 
f6aef7a
439fbe0
 
 
 
 
 
 
 
 
 
 
 
 
 
c305d1d
 
f6aef7a
 
c305d1d
f6aef7a
 
c305d1d
 
 
 
f6aef7a
 
 
 
c305d1d
3a166fd
c305d1d
 
 
 
3a166fd
c305d1d
 
 
11a0038
 
 
 
 
 
f6aef7a
 
 
a49252c
f6aef7a
 
c305d1d
 
f6aef7a
d40d041
c305d1d
f6aef7a
c305d1d
f6aef7a
 
a49252c
 
c305d1d
 
 
 
 
 
 
f6aef7a
 
a49252c
f6aef7a
c305d1d
 
 
 
 
 
 
f6aef7a
 
3d6e88e
f6aef7a
3d6e88e
f6aef7a
3d6e88e
 
 
 
a49252c
c305d1d
3d6e88e
a49252c
3d6e88e
 
 
 
 
c305d1d
f6aef7a
3d6e88e
 
 
 
 
 
 
 
 
 
c305d1d
a49252c
3d6e88e
c305d1d
 
f6aef7a
c305d1d
f6aef7a
c305d1d
 
 
 
f6aef7a
11a0038
f6aef7a
 
 
 
 
c305d1d
 
 
 
 
f6aef7a
 
c305d1d
 
f6aef7a
c305d1d
 
d40d041
f6aef7a
c305d1d
 
f6aef7a
c305d1d
 
 
 
d789521
f6aef7a
e9271be
f6aef7a
c305d1d
f6aef7a
 
 
 
c305d1d
319aad8
f6aef7a
 
 
c305d1d
f6aef7a
 
 
319aad8
c305d1d
f6aef7a
 
 
 
e9271be
f6aef7a
 
 
 
c305d1d
 
 
 
 
f6aef7a
c305d1d
 
 
 
f6aef7a
 
c305d1d
 
 
 
f6aef7a
 
 
c305d1d
 
 
 
 
 
 
 
 
 
 
f6aef7a
 
c305d1d
f6aef7a
c305d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a49252c
c305d1d
 
 
 
 
 
 
 
 
 
a49252c
 
 
c305d1d
a49252c
 
 
c305d1d
a49252c
c305d1d
a49252c
 
 
 
 
 
 
 
 
 
 
 
 
 
c305d1d
f6aef7a
98058c0
f6aef7a
98058c0
f6aef7a
 
 
 
 
 
 
98058c0
e9271be
 
c305d1d
f6aef7a
c305d1d
11a0038
c305d1d
e9271be
c305d1d
e9271be
c305d1d
f6aef7a
c305d1d
f6aef7a
c305d1d
f6aef7a
c305d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
f6aef7a
e9271be
f6aef7a
e9271be
 
f6aef7a
c305d1d
e9271be
 
f6aef7a
c305d1d
e9271be
c305d1d
 
e9271be
f6aef7a
 
c305d1d
e9271be
 
 
 
 
 
 
 
 
 
 
f6aef7a
 
 
e9271be
ad909a3
c305d1d
f6aef7a
c305d1d
f6aef7a
c305d1d
e9271be
c305d1d
 
 
 
f6aef7a
c305d1d
a92e352
c305d1d
 
ad909a3
c305d1d
 
 
 
 
 
 
 
e9271be
 
 
 
 
a49252c
e9271be
 
 
 
 
 
 
 
 
 
c305d1d
a49252c
0787c72
f6aef7a
11a0038
f6aef7a
 
 
 
 
c305d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9271be
f6aef7a
c305d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
98058c0
f6aef7a
e9271be
c305d1d
 
 
 
 
 
 
 
 
 
 
 
 
a4310db
c305d1d
 
 
a4310db
 
 
 
 
 
c305d1d
 
e9271be
c305d1d
 
 
 
 
 
 
 
 
f6aef7a
c305d1d
f6aef7a
 
c305d1d
 
f6aef7a
e9271be
 
f6aef7a
c305d1d
 
 
 
 
e9271be
 
f6aef7a
 
 
 
e9271be
f6aef7a
c305d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6aef7a
 
 
 
 
c305d1d
11a0038
 
c305d1d
 
 
 
e9271be
 
f6aef7a
 
 
c305d1d
 
f6aef7a
e9271be
 
 
 
c305d1d
 
f6aef7a
 
 
e9271be
 
f6aef7a
 
 
c305d1d
 
 
 
 
f6aef7a
 
c305d1d
e9271be
ad909a3
c305d1d
e9271be
c305d1d
 
 
e9271be
 
 
c305d1d
 
11a0038
a49252c
e9271be
f6aef7a
 
 
 
e9271be
 
 
 
c305d1d
 
 
f6aef7a
 
 
e9271be
c305d1d
11a0038
f6aef7a
c305d1d
e9271be
c305d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9271be
c305d1d
 
e9271be
c305d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e9271be
f6aef7a
c305d1d
e9271be
f6aef7a
 
 
e9271be
f6aef7a
e9271be
f6aef7a
e9271be
f6aef7a
c305d1d
f6aef7a
c305d1d
f6aef7a
c305d1d
 
 
 
 
 
 
98058c0
f6aef7a
c305d1d
 
 
a92e352
f6aef7a
 
 
 
 
c305d1d
 
f6aef7a
c305d1d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f6aef7a
 
c305d1d
 
 
 
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
# app.py (Refactored - Client State Save, Action Log, Radio Tools)
import streamlit as st
import asyncio
import uuid
from datetime import datetime
import os
import random
import time
import hashlib
import glob
import base64
import io
import streamlit.components.v1 as components
import edge_tts # Keep for TTS
import nest_asyncio
import re
import pytz
import shutil
# from PyPDF2 import PdfReader # Keep if PDF tab is kept
import threading # Keep lock for potential future use or background tasks
import json
import zipfile
from dotenv import load_dotenv
# from streamlit_marquee import streamlit_marquee # Keep import if used
from collections import defaultdict, Counter, deque # Use deque for action log
# import pandas as pd # Removed dependency
from streamlit_js_eval import streamlit_js_eval
from PIL import Image # Needed for paste_image_component

# ==============================================================================
# Configuration & Constants
# ==============================================================================
st.set_page_config(page_title="🌍🏗️ World Action Builder 🏆", page_icon="🏗️", layout="wide", initial_sidebar_state="expanded")
nest_asyncio.apply() # Patch asyncio

# General Constants
Site_Name = '🌍🏗️ World Action Builder'
MEDIA_DIR = "."
STATE_FILE = "user_state.txt"
DEFAULT_TTS_VOICE = "en-US-AriaNeural"

# User/Chat Constants
FUN_USERNAMES = {
    "BuilderBot 🤖": "en-US-AriaNeural", "WorldWeaver 🕸️": "en-US-JennyNeural",
    "Terraformer 🌱": "en-GB-SoniaNeural", "SkyArchitect ☁️": "en-AU-NatashaNeural",
    "PixelPainter 🎨": "en-CA-ClaraNeural", "VoxelVortex 🌪️": "en-US-GuyNeural",
    "CosmicCrafter ✨": "en-GB-RyanNeural", "GeoGuru 🗺️": "en-AU-WilliamNeural",
    "BlockBard 🧱": "en-CA-LiamNeural", "SoundSculptor 🔊": "en-US-AnaNeural",
    # Add more if desired
}
# Define available voices based on the dictionary (needed for TTS)
EDGE_TTS_VOICES = list(set(FUN_USERNAMES.values()))
DEFAULT_TTS_VOICE = "en-US-AriaNeural" # Keep a default
CHAT_DIR = "chat_logs"

# Directories
CHAT_DIR = "chat_logs"
AUDIO_CACHE_DIR = "audio_cache"
AUDIO_DIR = "audio_logs"
SAVED_WORLDS_DIR = "saved_worlds"

# World Builder Constants
PLOT_WIDTH = 50.0
PLOT_DEPTH = 50.0
WORLD_STATE_FILE_MD_PREFIX = "🌍_"
MAX_ACTION_LOG_SIZE = 30 # Max entries in sidebar action log

# File Emojis
FILE_EMOJIS = {"md": "📝", "mp3": "🎵", "png": "🖼️", "mp4": "🎥", "zip": "📦", "json": "📄"}

# Primitives Map (Tool Name -> Emoji for Radio Button Display)
PRIMITIVE_MAP = {
    "Tree": "🌳", "Rock": "🗿", "Simple House": "🏛️", "Pine Tree": "🌲", "Brick Wall": "🧱",
    "Sphere": "🔵", "Cube": "📦", "Cylinder": "🧴", "Cone": "🍦", "Torus": "🍩",
    "Mushroom": "🍄", "Cactus": "🌵", "Campfire": "🔥", "Star": "⭐", "Gem": "💎",
    "Tower": "🗼", "Barrier": "🚧", "Fountain": "⛲", "Lantern": "🏮", "Sign Post": "팻"
}
# Add None option for clearing tool
TOOLS_MAP = {"None": "🚫"}
TOOLS_MAP.update({name: emoji for emoji, name in PRIMITIVE_MAP.items()}) # Combine for radio options

# --- Directories ---
for d in [CHAT_DIR, AUDIO_DIR, AUDIO_CACHE_DIR, SAVED_WORLDS_DIR]:
    os.makedirs(d, exist_ok=True)

# --- API Keys (Placeholder) ---
load_dotenv()

# ==============================================================================
# Utility Functions
# ==============================================================================
def get_current_time_str(tz='UTC'):
    try: timezone = pytz.timezone(tz); now_aware = datetime.now(timezone)
    except Exception: now_aware = datetime.now(pytz.utc)
    return now_aware.strftime('%Y%m%d_%H%M%S')

def clean_filename_part(text, max_len=25): # Shorter max len
    if not isinstance(text, str): text = "invalid_name"
    text = re.sub(r'\s+', '_', text); text = re.sub(r'[^\w\-.]', '', text)
    return text[:max_len]

def run_async(async_func, *args, **kwargs):
    """Runs an async function safely from a sync context using create_task."""
    try: loop = asyncio.get_running_loop(); return loop.create_task(async_func(*args, **kwargs))
    except RuntimeError:
        try: return asyncio.run(async_func(*args, **kwargs))
        except Exception as e: print(f"Error run_async new loop: {e}"); return None
    except Exception as e: print(f"Error run_async schedule task: {e}"); return None

def ensure_dir(dir_path): os.makedirs(dir_path, exist_ok=True)

# ==============================================================================
# World State File Handling (Markdown + JSON)
# ==============================================================================
def generate_world_save_filename(username="User", world_name="World"):
    """Generates filename including username, world name, timestamp."""
    timestamp = get_current_time_str()
    clean_user = clean_filename_part(username, 15)
    clean_world = clean_filename_part(world_name, 20)
    rand_hash = hashlib.md5(str(time.time()).encode() + username.encode() + world_name.encode()).hexdigest()[:4]
    return f"{WORLD_STATE_FILE_MD_PREFIX}{clean_world}_by_{clean_user}_{timestamp}_{rand_hash}.md"

def parse_world_filename(filename):
    """Extracts info from filename if possible, otherwise returns defaults."""
    basename = os.path.basename(filename)
    # Check prefix and suffix
    if basename.startswith(WORLD_STATE_FILE_MD_PREFIX) and basename.endswith(".md"):
        core_name = basename[len(WORLD_STATE_FILE_MD_PREFIX):-3]
        parts = core_name.split('_')
        # Check if structure matches Name_by_User_Timestamp_Hash
        if len(parts) >= 5 and parts[-3] == "by":
            timestamp_str = parts[-2]
            username = parts[-4]
            world_name = " ".join(parts[:-4]) # Join potential name parts
            dt_obj = None
            try: # Try parsing timestamp
                dt_obj = datetime.strptime(timestamp_str, '%Y%m%d_%H%M%S')
                dt_obj = pytz.utc.localize(dt_obj) # Assume UTC
            except (ValueError, pytz.exceptions.AmbiguousTimeError, pytz.exceptions.NonExistentTimeError):
                dt_obj = None # Parsing failed
            return {"name": world_name or "Untitled", "user": username, "timestamp": timestamp_str, "dt": dt_obj, "filename": filename}

    # Fallback for unknown format or if parsing above failed
    # This section runs if the 'if' conditions above weren't fully met
    # print(f"Using fallback parsing for filename: {basename}") # Debugging log
    dt_fallback = None
    try: # Try getting modification time
        mtime = os.path.getmtime(filename)
        dt_fallback = datetime.fromtimestamp(mtime, tz=pytz.utc)
    except Exception: # Ignore errors getting mtime
        pass
    # CORRECTED INDENTATION: This return belongs to the main function scope for the fallback case
    return {"name": basename.replace('.md','').replace(WORLD_STATE_FILE_MD_PREFIX, ''), "user": "Unknown", "timestamp": "Unknown", "dt": dt_fallback, "filename": filename}

    
def save_world_to_md(target_filename_base, world_data_dict):
    """Saves the provided world state dictionary to a specific MD file."""
    save_path = os.path.join(SAVED_WORLDS_DIR, target_filename_base)
    print(f"Saving {len(world_data_dict)} objects to MD file: {save_path}...")
    success = False
    # No lock needed as we're writing data received from JS, not modifying shared state directly
    parsed_info = parse_world_filename(save_path)
    timestamp_save = get_current_time_str()
    md_content = f"""# World State: {parsed_info['name']} by {parsed_info['user']}
* **File Saved:** {timestamp_save} (UTC)
* **Source Timestamp:** {parsed_info['timestamp']}
* **Objects:** {len(world_data_dict)}

```json
{json.dumps(world_data_dict, indent=2)}
```"""
    try:
        ensure_dir(SAVED_WORLDS_DIR);
        with open(save_path, 'w', encoding='utf-8') as f: f.write(md_content)
        print(f"World state saved successfully to {target_filename_base}"); success = True
    except Exception as e: print(f"Error saving world state to {save_path}: {e}")
    return success

def load_world_from_md(filename_base):
    """Loads world state dict from an MD file (basename), DOES NOT update global state."""
    load_path = os.path.join(SAVED_WORLDS_DIR, filename_base)
    print(f"Loading world state dictionary from MD file: {load_path}...")
    if not os.path.exists(load_path): st.error(f"World file not found: {filename_base}"); return None
    try:
        with open(load_path, 'r', encoding='utf-8') as f: content = f.read()
        json_match = re.search(r"```json\s*(\{[\s\S]*?\})\s*```", content, re.IGNORECASE)
        if not json_match: st.error(f"Could not find valid JSON block in {filename_base}"); return None
        world_data_dict = json.loads(json_match.group(1))
        print(f"Parsed {len(world_data_dict)} objects from {filename_base}.")
        return world_data_dict # Return the dictionary
    except json.JSONDecodeError as e: st.error(f"Invalid JSON found in {filename_base}: {e}"); return None
    except Exception as e: st.error(f"Error loading world state from {filename_base}: {e}"); st.exception(e); return None

def get_saved_worlds():
    """Scans the saved worlds directory for world MD files and parses them."""
    try:
        ensure_dir(SAVED_WORLDS_DIR);
        world_files = glob.glob(os.path.join(SAVED_WORLDS_DIR, f"{WORLD_STATE_FILE_MD_PREFIX}*.md"))
        parsed_worlds = [parse_world_filename(f) for f in world_files]
        parsed_worlds.sort(key=lambda x: x['dt'] if x['dt'] else datetime.min.replace(tzinfo=pytz.utc), reverse=True)
        return parsed_worlds
    except Exception as e: print(f"Error scanning saved worlds: {e}"); st.error(f"Could not scan saved worlds: {e}"); return []

# ==============================================================================
# User State & Session Init
# ==============================================================================
def save_username(username): # Keep as is
    try:
        with open(STATE_FILE, 'w') as f: f.write(username)
    except Exception as e: print(f"Failed save username: {e}")

def load_username(): # Keep as is
    if os.path.exists(STATE_FILE):
        try:
            with open(STATE_FILE, 'r') as f: return f.read().strip()
        except Exception as e: print(f"Failed load username: {e}")
    return None

def init_session_state():
    """Initializes Streamlit session state variables."""
    defaults = {
        'last_chat_update': 0, 'message_input': "", 'audio_cache': {},
        'tts_voice': DEFAULT_TTS_VOICE, 'chat_history': [], 'enable_audio': True,
        'download_link_cache': {}, 'username': None, 'autosend': False,
        'last_message': "",
        'selected_object': 'None', # Current building tool
        'current_world_file': None, # Track loaded world filename (basename)
        'new_world_name': "MyWorld",
        'action_log': deque(maxlen=MAX_ACTION_LOG_SIZE), # Use deque for fixed-size log
        'world_to_load_data': None, # Temp storage for state loaded from file before sending to JS
        'js_object_placed_data': None # Temp storage for data coming from JS place event
    }
    for k, v in defaults.items():
        if k not in st.session_state:
            if k == 'action_log': st.session_state[k] = deque(maxlen=MAX_ACTION_LOG_SIZE)
            else: st.session_state[k] = v
    # Ensure complex types initialized correctly if state is reloaded badly
    if not isinstance(st.session_state.chat_history, list): st.session_state.chat_history = []
    if not isinstance(st.session_state.audio_cache, dict): st.session_state.audio_cache = {}
    if not isinstance(st.session_state.download_link_cache, dict): st.session_state.download_link_cache = {}
    if not isinstance(st.session_state.action_log, deque): st.session_state.action_log = deque(maxlen=MAX_ACTION_LOG_SIZE)

# ==============================================================================
# Action Log Helper
# ==============================================================================
def add_action_log(message):
    """Adds a message to the session's action log."""
    if 'action_log' not in st.session_state:
        st.session_state.action_log = deque(maxlen=MAX_ACTION_LOG_SIZE)
    timestamp = datetime.now().strftime("%H:%M:%S")
    st.session_state.action_log.appendleft(f"[{timestamp}] {message}") # Add to front

# ==============================================================================
# JS Communication Handler Function (Called from JS via streamlit_js_eval)
# ==============================================================================
# NOTE: Functions called by streamlit_js_eval run in the main Python thread.
# Avoid blocking operations here. Use session state to pass data if needed.

def handle_js_object_placed(data):
    """Callback triggered by JS when an object is placed."""
    print(f"Python received object placed event: {data}") # Debug
    if isinstance(data, dict) and data.get('obj_id') and data.get('type'):
        # Store data in session state to be processed in the main script flow
        st.session_state.js_object_placed_data = data
        # Add to action log immediately
        add_action_log(f"Placed {data.get('type', 'object')} ({data.get('obj_id', 'N/A')[:6]}...)")
        # Need a rerun for the main loop to process st.session_state.js_object_placed_data
        # However, triggering rerun from here can be complex.
        # Let the natural Streamlit flow handle picking it up.
    else:
        print("Received invalid object placement data from JS.")
    return True # Acknowledge receipt to JS


# ==============================================================================
# Audio / TTS / Chat / File Handling Helpers (Unchanged from previous)
# ==============================================================================
# (Include the full code for these helpers: clean_text_for_tts, create_file,
#  get_download_link, async_edge_tts_generate, play_and_download_audio,
#  save_chat_entry, load_chat_history, create_zip_of_files, delete_files,
#  save_pasted_image, paste_image_component, AudioProcessor, process_pdf_tab)
# --- Placeholder for brevity ---
def clean_text_for_tts(text): # ... implementation ...
    if not isinstance(text, str): return "No text"
    text = re.sub(r'\[([^\]]+)\]\([^\)]+\)', r'\1', text); text = re.sub(r'[#*_`!]', '', text)
    text = ' '.join(text.split()); return text[:250] or "No text"
def create_file(content, username, file_type="md", save_path=None): # ... implementation ...
    if not save_path: filename = generate_filename(content, username, file_type); save_path = os.path.join(MEDIA_DIR, filename)
    ensure_dir(os.path.dirname(save_path))
    try:
        with open(save_path, 'w', encoding='utf-8') as f: f.write(content); return save_path
    except Exception as e: print(f"Error creating file {save_path}: {e}"); return None
def get_download_link(file_path, file_type="md"): # ... implementation ...
    if not file_path or not os.path.exists(file_path): basename = os.path.basename(file_path) if file_path else "N/A"; return f"<small>Not found: {basename}</small>"
    try: mtime = os.path.getmtime(file_path)
    except OSError: mtime = 0
    cache_key = f"dl_{file_path}_{mtime}";
    if 'download_link_cache' not in st.session_state: st.session_state.download_link_cache = {}
    if cache_key not in st.session_state.download_link_cache:
        try:
            with open(file_path, "rb") as f: b64 = base64.b64encode(f.read()).decode()
            mime_types = {"md": "text/markdown", "mp3": "audio/mpeg", "png": "image/png", "mp4": "video/mp4", "zip": "application/zip", "json": "application/json"}
            basename = os.path.basename(file_path)
            link_html = f'<a href="data:{mime_types.get(file_type, "application/octet-stream")};base64,{b64}" download="{basename}" title="Download {basename}">{FILE_EMOJIS.get(file_type, "📄")}</a>'
            st.session_state.download_link_cache[cache_key] = link_html
        except Exception as e: print(f"Error generating DL link for {file_path}: {e}"); return f"<small>Err</small>"
    return st.session_state.download_link_cache.get(cache_key, "<small>CacheErr</small>")
async def async_edge_tts_generate(text, voice, username): # ... implementation ...
    if not text: return None
    cache_key = hashlib.md5(f"{text[:150]}_{voice}".encode()).hexdigest();
    if 'audio_cache' not in st.session_state: st.session_state.audio_cache = {}
    cached_path = st.session_state.audio_cache.get(cache_key);
    if cached_path and os.path.exists(cached_path): return cached_path
    text_cleaned = clean_text_for_tts(text);
    if not text_cleaned or text_cleaned == "No text": return None
    filename_base = generate_filename(text_cleaned, username, "mp3"); save_path = os.path.join(AUDIO_DIR, filename_base);
    ensure_dir(AUDIO_DIR)
    try:
        communicate = edge_tts.Communicate(text_cleaned, voice); await communicate.save(save_path);
        if os.path.exists(save_path) and os.path.getsize(save_path) > 0: st.session_state.audio_cache[cache_key] = save_path; return save_path
        else: print(f"Audio file {save_path} failed generation."); return None
    except Exception as e: print(f"Edge TTS Error: {e}"); return None
def play_and_download_audio(file_path): # ... implementation ...
    if file_path and os.path.exists(file_path):
        try: st.audio(file_path); file_type = file_path.split('.')[-1]; st.markdown(get_download_link(file_path, file_type), unsafe_allow_html=True)
        except Exception as e: st.error(f"Audio display error for {os.path.basename(file_path)}: {e}")
async def save_chat_entry(username, message, voice, is_markdown=False): # ... implementation ...
    if not message.strip(): return None, None
    timestamp_str = get_current_time_str(); entry = f"[{timestamp_str}] {username} ({voice}): {message}" if not is_markdown else f"[{timestamp_str}] {username} ({voice}):\n```markdown\n{message}\n```"
    md_filename_base = generate_filename(message, username, "md"); md_file_path = os.path.join(CHAT_DIR, md_filename_base);
    md_file = create_file(entry, username, "md", save_path=md_file_path)
    if 'chat_history' not in st.session_state: st.session_state.chat_history = [];
    st.session_state.chat_history.append(entry)
    audio_file = None;
    if st.session_state.get('enable_audio', True): tts_message = message ; audio_file = await async_edge_tts_generate(tts_message, voice, username)
    return md_file, audio_file
async def load_chat_history(): # ... implementation ...
     if 'chat_history' not in st.session_state: st.session_state.chat_history = []
     if not st.session_state.chat_history:
          ensure_dir(CHAT_DIR); print("Loading chat history from files...")
          chat_files = sorted(glob.glob(os.path.join(CHAT_DIR, "*.md")), key=os.path.getmtime); loaded_count = 0
          temp_history = []
          for f_path in chat_files:
               try:
                    with open(f_path, 'r', encoding='utf-8') as file: temp_history.append(file.read().strip()); loaded_count += 1
               except Exception as e: print(f"Err read chat {f_path}: {e}")
          st.session_state.chat_history = temp_history
          print(f"Loaded {loaded_count} chat entries from files.")
     return st.session_state.chat_history
def create_zip_of_files(files_to_zip, prefix="Archive"): # ... implementation ...
    if not files_to_zip: st.warning("No files provided to zip."); return None
    timestamp = format_timestamp_prefix(f"Zip_{prefix}"); zip_name = f"{prefix}_{timestamp}.zip"
    try:
        print(f"Creating zip: {zip_name}...");
        with zipfile.ZipFile(zip_name, 'w', zipfile.ZIP_DEFLATED) as z:
            for f in files_to_zip:
                 if os.path.exists(f): z.write(f, os.path.basename(f))
                 else: print(f"Skip zip missing: {f}")
        print("Zip success."); st.success(f"Created {zip_name}"); return zip_name
    except Exception as e: print(f"Zip failed: {e}"); st.error(f"Zip failed: {e}"); return None
def delete_files(file_patterns, exclude_files=None): # ... implementation ...
    protected = [STATE_FILE, "app.py", "index.html", "requirements.txt", "README.md"]
    current_world_base = st.session_state.get('current_world_file')
    if current_world_base: protected.append(current_world_base)
    if exclude_files: protected.extend(exclude_files)
    deleted_count = 0; errors = 0
    for pattern in file_patterns:
         pattern_path = pattern
         print(f"Attempting to delete files matching: {pattern_path}")
         try:
              files_to_delete = glob.glob(pattern_path)
              if not files_to_delete: print(f"No files found for pattern: {pattern}"); continue
              for f_path in files_to_delete:
                   basename = os.path.basename(f_path)
                   if os.path.isfile(f_path) and basename not in protected:
                        try: os.remove(f_path); print(f"Deleted: {f_path}"); deleted_count += 1
                        except Exception as e: print(f"Failed delete {f_path}: {e}"); errors += 1
                   elif os.path.isdir(f_path): print(f"Skipping directory: {f_path}")
         except Exception as glob_e: print(f"Error matching pattern {pattern}: {glob_e}"); errors += 1
    msg = f"Deleted {deleted_count} files.";
    if errors > 0: msg += f" Encountered {errors} errors."; st.warning(msg)
    elif deleted_count > 0: st.success(msg)
    else: st.info("No matching files found to delete.")
    st.session_state['download_link_cache'] = {}; st.session_state['audio_cache'] = {}
async def save_pasted_image(image, username): # ... implementation ...
     if not image: return None
     try: img_hash = hashlib.md5(image.tobytes()).hexdigest()[:8]; timestamp = format_timestamp_prefix(username); filename = f"{timestamp}_pasted_{img_hash}.png"; filepath = os.path.join(MEDIA_DIR, filename); image.save(filepath, "PNG"); print(f"Pasted image saved: {filepath}"); return filepath
     except Exception as e: print(f"Failed image save: {e}"); return None
def paste_image_component(): # ... implementation ...
      pasted_img = None; img_type = None
      paste_input_value = st.text_area("Paste Image Data Here", key="paste_input_area", height=50, value=st.session_state.get('paste_image_base64_input', ""))
      if st.button("Process Pasted Image 📋", key="process_paste_button"):
           st.session_state.paste_image_base64_input = paste_input_value
           if paste_input_value and paste_input_value.startswith('data:image'):
               try:
                   mime_type = paste_input_value.split(';')[0].split(':')[1]; base64_str = paste_input_value.split(',')[1]; img_bytes = base64.b64decode(base64_str); pasted_img = Image.open(io.BytesIO(img_bytes)); img_type = mime_type.split('/')[1]
                   st.image(pasted_img, caption=f"Pasted ({img_type.upper()})", width=150); st.session_state.paste_image_base64 = base64_str
                   st.session_state.paste_image_base64_input = ""
                   st.rerun()
               except ImportError: st.error("Pillow library needed for image pasting.")
               except Exception as e: st.error(f"Img decode err: {e}"); st.session_state.paste_image_base64 = ""; st.session_state.paste_image_base64_input = paste_input_value
           else: st.warning("No valid image data pasted."); st.session_state.paste_image_base64 = ""; st.session_state.paste_image_base64_input = paste_input_value
      processed_b64 = st.session_state.get('paste_image_base64', '')
      if processed_b64:
           try: img_bytes = base64.b64decode(processed_b64); return Image.open(io.BytesIO(img_bytes))
           except Exception: return None
      return None
class AudioProcessor: # ... implementation ...
      def __init__(self): self.cache_dir=AUDIO_CACHE_DIR; ensure_dir(self.cache_dir); self.metadata=json.load(open(f"{self.cache_dir}/metadata.json", 'r')) if os.path.exists(f"{self.cache_dir}/metadata.json") else {}
      def _save_metadata(self):
            try:
                 with open(f"{self.cache_dir}/metadata.json", 'w') as f: json.dump(self.metadata, f, indent=2)
            except Exception as e: print(f"Failed metadata save: {e}")
      async def create_audio(self, text, voice='en-US-AriaNeural'):
            cache_key=hashlib.md5(f"{text[:150]}:{voice}".encode()).hexdigest(); cache_path=os.path.join(self.cache_dir, f"{cache_key}.mp3");
            if cache_key in self.metadata and os.path.exists(cache_path): return cache_path
            text_cleaned=clean_text_for_tts(text);
            if not text_cleaned: return None
            ensure_dir(os.path.dirname(cache_path))
            try:
                 communicate=edge_tts.Communicate(text_cleaned,voice); await communicate.save(cache_path)
                 if os.path.exists(cache_path) and os.path.getsize(cache_path) > 0: self.metadata[cache_key]={'timestamp': datetime.now().isoformat(), 'text_length': len(text_cleaned), 'voice': voice}; self._save_metadata(); return cache_path
                 else: return None
            except Exception as e: print(f"TTS Create Audio Error: {e}"); return None
# def process_pdf_tab(pdf_file, max_pages, voice): # ... implementation ... (Keep if needed)


# ==============================================================================
# Streamlit UI Layout Functions
# ==============================================================================

def render_sidebar():
    """Renders the Streamlit sidebar contents."""
    with st.sidebar:
        st.header("💾 World Management")

        # --- World Save ---
        current_world_name = "Live State"
        current_file = st.session_state.get('current_world_file')
        if current_file:
            parsed = parse_world_filename(os.path.join(SAVED_WORLDS_DIR, current_file))
            current_world_name = parsed.get("name", current_file)

        save_button_label = f"💾 Save '{current_world_name}'" if current_file else "💾 Save Live State as New..."
        if st.button(save_button_label, key="sidebar_save_world", help="Save the current state of the 3D world."):
            with st.spinner("Requesting world state from client..."):
                # Ask JS for the current world state
                js_world_state_str = streamlit_js_eval("getWorldStateForSave();", key="get_world_state_js", want_result=True)

            if js_world_state_str:
                try:
                    world_data_dict = json.loads(js_world_state_str)
                    if isinstance(world_data_dict, dict):
                        save_filename = ""
                        if current_file: # Overwrite existing file
                             save_filename = current_file
                             op_text = f"Overwriting '{current_world_name}'..."
                        else: # Save as new - prompt for name? Use session state?
                            world_name_to_save = st.session_state.get("new_world_name", "NewWorld") # Get name from state
                            if not world_name_to_save.strip(): world_name_to_save = "NewWorld"
                            save_filename = generate_world_save_filename(st.session_state.username, world_name_to_save)
                            op_text = f"Saving as new version '{world_name_to_save}'..."

                        with st.spinner(op_text):
                            if save_world_to_md(save_filename, world_data_dict):
                                st.success(f"World saved as {save_filename}")
                                add_action_log(f"Saved world: {save_filename}")
                                st.session_state.current_world_file = save_filename # Track saved file
                                st.rerun() # Refresh sidebar list
                            else:
                                st.error("Failed to save world state to file.")
                    else:
                         st.error("Received invalid world state format from client.")
                except json.JSONDecodeError:
                    st.error("Failed to decode world state received from client.")
                except Exception as e:
                     st.error(f"Error during save process: {e}")
            else:
                st.warning("Did not receive world state from client.")
        # Input for "Save As New" name (used if no file loaded)
        if not current_file:
             st.text_input("World Name for Save:", key="new_world_name", value=st.session_state.get('new_world_name', 'MyWorld'))


        # --- World Load ---
        st.markdown("---")
        st.header("📂 Load World")
        saved_worlds = get_saved_worlds()

        if not saved_worlds:
             st.caption("No saved worlds found.")
        else:
             st.caption("Click to load a saved state.")
             # Display load buttons and download links
             cols = st.columns([4, 1]) # Columns for name and download button
             with cols[0]: st.write("**Name** (User, Time)")
             with cols[1]: st.write("**DL**")
             display_limit = 15
             for i, world_info in enumerate(saved_worlds):
                f_basename = os.path.basename(world_info['filename'])
                f_fullpath = os.path.join(SAVED_WORLDS_DIR, f_basename) # Reconstruct full path
                display_name = world_info.get('name', f_basename)
                user = world_info.get('user', 'N/A')
                timestamp = world_info.get('timestamp', 'N/A')
                display_text = f"{display_name} ({user}, {timestamp})"

                # Logic for expander
                is_last_displayed = i == display_limit -1
                show_expander_trigger = len(saved_worlds) > display_limit and is_last_displayed

                container = st
                if show_expander_trigger and i == display_limit :
                     container = st.expander(f"Show {len(saved_worlds)-display_limit} more...")

                if i < display_limit or show_expander_trigger : # Render items within limit or inside expander
                     with container:
                          # Special handling to render first item inside expander if triggered
                          if show_expander_trigger and i == display_limit:
                              col1_exp, col2_exp, col3_exp = st.columns([3, 1, 1]);
                              with col1_exp: btn_load = st.button(f"{display_text}", key=f"load_{f_basename}", help=f"Load {f_basename}", use_container_width=True)
                              with col3_exp: st.markdown(get_download_link(f_fullpath, "md"), unsafe_allow_html=True)
                          # Render items normally (either before limit or after limit inside expander)
                          elif i < display_limit or not show_expander_trigger:
                               col1, col2, col3 = st.columns([3, 1, 1]) # Added extra col for button
                               with col1: st.write(f"<small>{display_text}</small>", unsafe_allow_html=True)
                               with col2: btn_load = st.button("Load", key=f"load_{f_basename}", help=f"Load {f_basename}")
                               with col3: st.markdown(get_download_link(f_fullpath, "md"), unsafe_allow_html=True)
                          else: # Render remaining items inside expander
                                for world_info_more in saved_worlds[display_limit+1:]: # Iterate remaining
                                    f_bn_more=os.path.basename(world_info_more['filename']); f_fp_more=os.path.join(SAVED_WORLDS_DIR, f_bn_more); dn_more=world_info_more.get('name',f_bn_more); u_more=world_info_more.get('user','N/A'); ts_more=world_info_more.get('timestamp','N/A')
                                    disp_more = f"{dn_more} ({u_more}, {ts_more})"
                                    colA, colB, colC = st.columns([3, 1, 1]);
                                    with colA: st.write(f"<small>{disp_more}</small>", unsafe_allow_html=True)
                                    with colB: btn_load_more = st.button("Load", key=f"load_{f_bn_more}", help=f"Load {f_bn_more}")
                                    with colC: st.markdown(get_download_link(f_fp_more, "md"), unsafe_allow_html=True)
                                    # Handle button click for these items
                                    if btn_load_more:
                                        print(f"Load button clicked for: {f_bn_more}")
                                        world_dict = load_world_from_md(f_bn_more)
                                        if world_dict is not None:
                                            st.session_state.world_to_load_data = world_dict # Store data to send to JS
                                            st.session_state.current_world_file = f_bn_more
                                            add_action_log(f"Loading world: {f_bn_more}")
                                            st.rerun() # Trigger rerun to send data via injection/call
                                        else: st.error(f"Failed to parse world file: {f_bn_more}")
                                break # Stop outer loop after handling expander fully

                     # Handle button click for items outside/at start of expander
                     if btn_load:
                          print(f"Load button clicked for: {f_basename}")
                          world_dict = load_world_from_md(f_basename)
                          if world_dict is not None:
                              st.session_state.world_to_load_data = world_dict
                              st.session_state.current_world_file = f_basename
                              add_action_log(f"Loading world: {f_basename}")
                              st.rerun()
                          else: st.error(f"Failed to parse world file: {f_basename}")

        # --- Build Tools ---
        st.markdown("---")
        st.header("🏗️ Build Tools")
        st.caption("Select an object to place.")
        # Use Radio Buttons for Tool Selection
        tool_options = list(TOOLS_MAP.keys()) # "None", "Tree", "Rock", etc.
        current_tool_name = st.session_state.get('selected_object', 'None')

        selected_tool = st.radio(
            "Select Tool:",
            options=tool_options,
            index=tool_options.index(current_tool_name) if current_tool_name in tool_options else 0,
            format_func=lambda name: f"{TOOLS_MAP.get(name, '')} {name}", # Show emoji + name
            key="tool_selector_radio",
            horizontal=True # Make radio horizontal if preferred
        )

# Handle tool change
        if selected_tool != current_tool_name:
            st.session_state.selected_object = selected_tool
            add_action_log(f"Selected tool: {selected_tool}")
            # CORRECTED: Use streamlit_js_eval instead of sync
            # This sends the update to JS without needing a return value immediately
            streamlit_js_eval(js_code=f"updateSelectedObjectType({json.dumps(selected_tool)});", key=f"update_tool_js_{selected_tool}")
            # Rerun to potentially update other UI elements if needed, though maybe optional
            # if only JS state needs update for the tool. Let's keep it for now.
            st.rerun()

        # --- Action Log ---
        st.markdown("---")
        st.header("📝 Action Log")
        log_container = st.container(height=200)
        with log_container:
            if 'action_log' in st.session_state and st.session_state.action_log:
                # Display log entries (newest first)
                st.code('\n'.join(st.session_state.action_log), language="log")
            else:
                st.caption("No actions recorded yet.")


        # --- Voice/User ---
        st.markdown("---")
        st.header("🗣️ Voice & User")
        current_username = st.session_state.get('username', list(FUN_USERNAMES.keys())[0]) if FUN_USERNAMES else "DefaultUser"
        username_options = list(FUN_USERNAMES.keys()) if FUN_USERNAMES else [current_username]; current_index = 0
        try: current_index = username_options.index(current_username)
        except ValueError: current_index = 0
        new_username = st.selectbox("Change Name/Voice", options=username_options, index=current_index, key="username_select", format_func=lambda x: x.split(" ")[0])
        if new_username != st.session_state.username:
            st.session_state.username = new_username;
            st.session_state.tts_voice = FUN_USERNAMES.get(new_username, DEFAULT_TTS_VOICE);
            save_username(st.session_state.username)
            # Add action log entry for name change?
            add_action_log(f"Username changed to {new_username}")
            st.rerun()
        st.session_state['enable_audio'] = st.toggle("Enable TTS Audio", value=st.session_state.get('enable_audio', True))


def render_main_content():
    """Renders the main content area with tabs."""
    st.title(f"{Site_Name} - User: {st.session_state.username}")

    # Check if we need to send newly loaded world data to JS
    world_data_to_load = st.session_state.pop('world_to_load_data', None) # Use pop to consume
    if world_data_to_load is not None:
        print(f"Sending loaded world state ({len(world_data_to_load)} objects) to JS...")
        # Call the JS function to load the state
        sync(js_code=f"loadWorldState({json.dumps(world_data_to_load)});", key="load_world_js")
        st.toast("World loaded in 3D view.", icon="🔄")


    # Check for object placement data coming back from JS
    # Use streamlit_js_eval to define a Python function callable from JS
    # Note: This function runs in the main Python thread when called by JS.
    # It should be quick and ideally just set session state.
    placed_object_data = streamlit_js_eval(
        js_code="""
            // Define function in JS global scope if not already defined
            if (typeof window.sendPlacedObjectToPython !== 'function') {
                window.sendPlacedObjectToPython = (objectData) => {
                    // Call the Python function 'handle_js_object_placed'
                    // Pass data as a JSON string for safety
                    streamlit_js_eval(`handle_js_object_placed(json_data='${JSON.stringify(objectData)}')`, key='js_place_event_handler');
                }
            }
            null; // Return null from initial setup call
        """,
        key="setup_js_place_event_handler"
    )

    # Check if the handler function was called (by checking if its key is in session_state)
    if 'js_place_event_handler' in st.session_state:
        # The handle_js_object_placed function (defined globally in Python)
        # would have been called and stored data in st.session_state.js_object_placed_data
        # Process data stored by the callback
        processed_data = st.session_state.pop('js_object_placed_data', None) # Use pop to consume
        if processed_data:
            print(f"Processing stored placed object data: {processed_data.get('obj_id')}")
            # Action log entry was already added in the handler function.
            # Object exists client-side. Server doesn't need to store it live, only on Save.
            # Might trigger a mini-rerun if processing changes UI elements? Unlikely here.
            # st.rerun() # Avoid rerun if possible, log entry is enough for now
            pass # Main processing (adding to server state dict) removed

        # Important: Clear the trigger key from session_state so it doesn't re-process
        del st.session_state['js_place_event_handler']


    # Define Tabs
    tab_world, tab_chat, tab_pdf, tab_files = st.tabs(["🏗️ World Builder", "🗣️ Chat", "📚 PDF Tools", "📂 Files & Settings"])

    # --- World Builder Tab ---
    with tab_world:
        st.header("Shared 3D World")
        st.caption("Place objects using sidebar tools. Use Sidebar to Save/Load.")
        current_file_basename = st.session_state.get('current_world_file', None)
        if current_file_basename:
             full_path_for_parse = os.path.join(SAVED_WORLDS_DIR, current_file_basename)
             if os.path.exists(full_path_for_parse): parsed = parse_world_filename(full_path_for_parse); st.info(f"Current World: **{parsed['name']}** (`{current_file_basename}`)")
             else: st.warning(f"Loaded file '{current_file_basename}' missing."); st.session_state.current_world_file = None
        else: st.info("Live State Active (Save to persist changes)")

        # Embed HTML Component
        html_file_path = 'index.html'
        try:
            with open(html_file_path, 'r', encoding='utf-8') as f: html_template = f.read()
            # Inject state needed by JS (Tool, Constants)
            # Initial world state is loaded via explicit JS call if world_to_load_data exists
            js_injection_script = f"""<script>
    window.USERNAME = {json.dumps(st.session_state.username)};
    window.SELECTED_OBJECT_TYPE = {json.dumps(st.session_state.selected_object)};
    window.PLOT_WIDTH = {json.dumps(PLOT_WIDTH)};
    window.PLOT_DEPTH = {json.dumps(PLOT_DEPTH)};
    // INITIAL_WORLD_OBJECTS injection removed - handled by loadWorldState JS call
    console.log("Streamlit State Injected:", {{ username: window.USERNAME, selectedObject: window.SELECTED_OBJECT_TYPE }});
</script>"""
            html_content_with_state = html_template.replace('</head>', js_injection_script + '\n</head>', 1)
            components.html(html_content_with_state, height=700, scrolling=False)
        except FileNotFoundError: st.error(f"CRITICAL ERROR: Could not find '{html_file_path}'.")
        except Exception as e: st.error(f"Error loading 3D component: {e}"); st.exception(e)

    # --- Chat Tab ---
    with tab_chat:
        st.header(f"💬 Chat") # Simplified header
        # Load chat history
        chat_history_list = st.session_state.get('chat_history', [])
        if not chat_history_list: chat_history_list = asyncio.run(load_chat_history()) # Load if empty

        chat_container = st.container(height=500)
        with chat_container:
             if chat_history_list: st.markdown("----\n".join(reversed(chat_history_list[-50:])))
             else: st.caption("No chat messages yet.")

        # Chat Input
        message_value = st.text_input("Your Message:", key="message_input", label_visibility="collapsed")
        send_button_clicked = st.button("Send Chat", key="send_chat_button")
        # Removed autosend for simplicity, can be added back
        if send_button_clicked:
            message_to_send = message_value
            if message_to_send.strip() and message_to_send != st.session_state.get('last_message', ''):
                st.session_state.last_message = message_to_send
                voice = st.session_state.get('tts_voice', DEFAULT_TTS_VOICE)
                # Save entry and generate audio (fire-and-forget)
                run_async(save_chat_entry, st.session_state.username, message_to_send, voice)
                st.session_state.message_input = "" # Clear state for next run
                st.rerun()
            elif send_button_clicked: st.toast("Message empty or same as last.")

    # --- PDF Tab ---
    with tab_pdf:
         st.header("📚 PDF Tools")
         pdf_file = st.file_uploader("Upload PDF for Audio Conversion", type="pdf", key="pdf_upload")
         max_pages = st.slider('Max Pages to Process', 1, 50, 10, key="pdf_pages")
         if pdf_file:
             if st.button("Process PDF to Audio", key="process_pdf_button"):
                 with st.spinner("Processing PDF... This may take time."):
                     process_pdf_tab(pdf_file, max_pages, st.session_state.tts_voice)

    # --- Files & Settings Tab ---
    with tab_files:
        st.header("📂 Files & Settings")
        st.subheader("💾 World Management")
        current_file_basename = st.session_state.get('current_world_file', None)

        # Save Current Version Button (if a world is loaded)
        if current_file_basename:
            full_path_for_parse = os.path.join(SAVED_WORLDS_DIR, current_file_basename)
            save_label = f"Save Changes to '{current_file_basename}'" # Default label
            if os.path.exists(full_path_for_parse): parsed = parse_world_filename(full_path_for_parse); save_label = f"Save Changes to '{parsed['name']}'"
            if st.button(save_label, key="save_current_world_files", help=f"Overwrite '{current_file_basename}'"):
                 if not os.path.exists(full_path_for_parse): st.error(f"Cannot save, file missing.")
                 else:
                     with st.spinner("Requesting state & saving..."):
                          js_world_state_str = streamlit_js_eval("getWorldStateForSave();", key="get_world_state_save_current", want_result=True)
                          if js_world_state_str:
                               try:
                                   world_data_dict = json.loads(js_world_state_str)
                                   if isinstance(world_data_dict, dict):
                                       if save_world_to_md(current_file_basename, world_data_dict):
                                           st.success("Current world saved!"); add_action_log(f"Saved world: {current_file_basename}")
                                       else: st.error("Failed to save.")
                                   else: st.error("Invalid format from client.")
                               except json.JSONDecodeError: st.error("Failed to decode state from client.")
                          else: st.warning("Did not receive world state from client.")
        else: st.info("Load a world from the sidebar to enable 'Save Changes'.")

        # Save As New Version Section
        st.subheader("Save As New Version")
        new_name_files = st.text_input("World Name:", key="new_world_name_files_tab", value=st.session_state.get('new_world_name', 'MyWorld'))
        if st.button("💾 Save Current View as New Version", key="save_new_version_files"):
             if new_name_files.strip():
                 with st.spinner(f"Requesting state & saving as '{new_name_files}'..."):
                      js_world_state_str = streamlit_js_eval("getWorldStateForSave();", key="get_world_state_save_new", want_result=True)
                      if js_world_state_str:
                           try:
                               world_data_dict = json.loads(js_world_state_str)
                               if isinstance(world_data_dict, dict):
                                   new_filename_base = generate_world_save_filename(st.session_state.username, new_name_files)
                                   if save_world_to_md(new_filename_base, world_data_dict):
                                       st.success(f"Saved as {new_filename_base}")
                                       st.session_state.current_world_file = new_filename_base; st.session_state.new_world_name = "MyWorld";
                                       add_action_log(f"Saved new world: {new_filename_base}")
                                       st.rerun()
                                   else: st.error("Failed to save new version.")
                               else: st.error("Invalid format from client.")
                           except json.JSONDecodeError: st.error("Failed to decode state from client.")
                      else: st.warning("Did not receive world state from client.")
             else: st.warning("Please enter a name.")

        # File Deletion
        st.subheader("🗑️ Delete Files")
        st.warning("Deletion is permanent!", icon="⚠️")
        col_del1, col_del2, col_del3, col_del4 = st.columns(4)
        with col_del1:
             if st.button("🗑️ Chats", key="del_chat_md"): delete_files([os.path.join(CHAT_DIR, "*.md")]); st.session_state.chat_history = []; st.rerun()
        with col_del2:
            if st.button("🗑️ Audio", key="del_audio_mp3"): delete_files([os.path.join(AUDIO_DIR, "*.mp3"), os.path.join(AUDIO_CACHE_DIR, "*.mp3")]); st.session_state.audio_cache = {}; st.rerun()
        with col_del3:
            if st.button("🗑️ Worlds", key="del_worlds_md"): delete_files([os.path.join(SAVED_WORLDS_DIR, f"{WORLD_STATE_FILE_MD_PREFIX}*.md")]); st.session_state.current_world_file = None; st.rerun()
        with col_del4:
            if st.button("🗑️ All Gen", key="del_all_gen"): delete_files([os.path.join(CHAT_DIR, "*.md"), os.path.join(AUDIO_DIR, "*.mp3"), os.path.join(AUDIO_CACHE_DIR, "*.mp3"), os.path.join(SAVED_WORLDS_DIR, "*.md"), os.path.join(MEDIA_DIR, "*.zip")]); st.session_state.chat_history = []; st.session_state.audio_cache = {}; st.session_state.current_world_file = None; st.rerun()

        # Download Archives
        st.subheader("📦 Download Archives")
        col_zip1, col_zip2, col_zip3 = st.columns(3)
        with col_zip1:
            if st.button("Zip Worlds"): create_zip_of_files(glob.glob(os.path.join(SAVED_WORLDS_DIR, f"{WORLD_STATE_FILE_MD_PREFIX}*.md")), "Worlds")
        with col_zip2:
            if st.button("Zip Chats"): create_zip_of_files(glob.glob(os.path.join(CHAT_DIR, "*.md")), "Chats")
        with col_zip3:
            if st.button("Zip Audio"): create_zip_of_files(glob.glob(os.path.join(AUDIO_DIR, "*.mp3")) + glob.glob(os.path.join(AUDIO_CACHE_DIR, "*.mp3")), "Audio")
        zip_files = sorted(glob.glob(os.path.join(MEDIA_DIR,"*.zip")), key=os.path.getmtime, reverse=True)
        if zip_files:
            st.caption("Existing Zip Files:")
            for zip_file in zip_files: st.markdown(get_download_link(zip_file, "zip"), unsafe_allow_html=True)
        else: st.caption("No zip archives found.")


# ==============================================================================
# Main Execution Logic
# ==============================================================================

def initialize_app():
    """Handles session init and initial world load."""
    init_session_state()
    # Load username here after init
    if not st.session_state.username:
        loaded_user = load_username()
        if loaded_user and loaded_user in FUN_USERNAMES:
             st.session_state.username = loaded_user
             st.session_state.tts_voice = FUN_USERNAMES[loaded_user]
        else:
             st.session_state.username = random.choice(list(FUN_USERNAMES.keys())) if FUN_USERNAMES else "User"
             st.session_state.tts_voice = FUN_USERNAMES.get(st.session_state.username, DEFAULT_TTS_VOICE)
             save_username(st.session_state.username) # Save the newly assigned name

    # Load initial world state (most recent) if not already handled by load button click
    # Check 'world_to_load_data' first - if present, it means a load was just triggered.
    if 'world_to_load_data' not in st.session_state or st.session_state.world_to_load_data is None:
        # Only load from file if no specific world load is pending
        if st.session_state.get('current_world_file') is None: # And no world currently selected
            print("Attempting initial load of most recent world...")
            saved_worlds = get_saved_worlds()
            if saved_worlds:
                 latest_world_file_basename = os.path.basename(saved_worlds[0]['filename'])
                 print(f"Loading most recent world on startup: {latest_world_file_basename}")
                 world_dict = load_world_from_md(latest_world_file_basename)
                 if world_dict is not None:
                      st.session_state.world_to_load_data = world_dict # Set data to be sent to JS
                      st.session_state.current_world_file = latest_world_file_basename # Update selection state
                 else: print("Failed to load most recent world.")
            else: print("No saved worlds found for initial load.")


if __name__ == "__main__":
    initialize_app() # Initialize state, load user, potentially load initial world data state
    render_sidebar() # Render sidebar UI
    render_main_content() # Render main UI content (includes logic to send loaded world data to JS)