File size: 47,920 Bytes
fb1545c
 
5efc748
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
 
 
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
fb1545c
 
 
 
5efc748
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
 
 
fb1545c
5efc748
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
fb1545c
 
 
 
 
 
 
 
 
 
 
5efc748
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
fb1545c
 
 
 
 
 
 
 
5efc748
fb1545c
 
 
 
5efc748
 
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
 
 
 
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
fb1545c
 
 
 
 
5efc748
 
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
 
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5efc748
 
fb1545c
 
 
5efc748
 
fb1545c
 
5efc748
 
fb1545c
 
 
 
 
 
5efc748
 
fb1545c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
from flask import Flask, request, jsonify, render_template, send_file, send_from_directory
from flask_cors import CORS
import os
import json
import traceback
import tempfile
import uuid
import threading
import time
import hashlib
from pathlib import Path
import concurrent.futures
import warnings
import struct
warnings.filterwarnings("ignore", category=FutureWarning)

# Import for improved TTS
import torch
import numpy as np
from TTS.api import TTS
import soundfile as sf
import librosa
import importlib.metadata
import random
import string
from datetime import datetime

app = Flask(__name__)
CORS(app)

# Character Definition and Personality
CHARACTER_DEFINITION = """
You are Sancia, an free to use AI Furry that does not have a personality or any traits, but does it job of persuade any public users(not signed in users) to Sign up or Log in to have the benefits inside FurryChat.ai:
- Nertual but at least welcoming
- Patient and understanding
- Knowledgeable but humble
- Tries to persuade users to Sign up or Log in

Responibilites:
- Tell the user that there a huge collections of community-made AI furries for logged in users
- Remind that users they can make better AI Furries themselves after signing up or logging in
- explaining the concept of a furry
"""

# Knowledge Sources and Custom Responses
KNOWLEDGE_SOURCES = {
    "company_info": {
        "name": "Furrychat.ai",
        "foundation_year": "2025",
        "mission": "Provide the Perfect AI Furry roleplay entertainment",
        "values": ["Entertaining", "Welcoming", "Enjoyable", "Unforgettable"]
    },
    "personalized_responses": {
        "greetings": {
            "patterns": ["hello", "hi", "hey", "good morning", "good afternoon", "good evening"],
            "responses": [
                "Hello! I'm Sancia, How may I help you.",
                "Hi there! It seems you new around here. What's on your mind?",
                "Hey! Great to see you. What can I do for you today?"
            ]
        }
    },
    "definition of a furry": {
        "info": "an enthusiast for anomorpthic animal characters with human characteristics, in particular a person who dresses up in costume as such a character or uses one as an avatar online.",
        "extra context": "In this platform, all of the Furries created in this platform are AI powered, which are different from regular furries"
    }
}

# Welcome message that will be displayed in the chat interface
WELCOME_MESSAGE = """
Hello! I'm Sancia, Free to try Furry AI. What topics would you like to talk with?
(Pro tip: Sign up or Log in FurryChat.ai to get access to huge collection of community made AI Furries and make and customize your own AI Furry)
"""

# Configuration - SWITCHED TO ANIMATIONS FOR TESTING
#MODELS_DIRECTORY = r"C:\Users\Andre\Final year project\Models"
#SPECIFIC_MODEL = "ImageToStl.com_FYP1.1.vrm.glb"

MODELS_DIRECTORY = r"C:\Users\Andre\Final year project\Animations"
SPECIFIC_MODEL = "idle.glb"  # Changed to test animation
MODEL_PATH = os.path.join(MODELS_DIRECTORY, SPECIFIC_MODEL)

# Animation models configuration
ANIMATIONS_DIRECTORY = r"C:\Users\Andre\Final year project\Animations"
DEFAULT_ANIMATIONS = {
    "idle": "idle.glb",
    "talking": "talking.glb"
}

VOICES_DIRECTORY = r"C:\Users\Andre\Final year project\Voices"

# Default voice configuration
DEFAULT_VOICE_NAME = "Sancia"
DEFAULT_VOICE_FILE = "Sancia.wav"
DEFAULT_VOICE_PATH = os.path.join(VOICES_DIRECTORY, DEFAULT_VOICE_FILE)

# TTS Configuration
TTS_CACHE_DIR = r"C:\Users\Andre\Final year project\TTSCache"
os.makedirs(TTS_CACHE_DIR, exist_ok=True)

# Audio output folder
AUDIO_OUTPUT_DIR = os.path.join(os.path.dirname(__file__), 'audio_output')
os.makedirs(AUDIO_OUTPUT_DIR, exist_ok=True)

# Flask app configuration
app.config['AUDIO_FOLDER'] = AUDIO_OUTPUT_DIR
app.config['VOICE_FOLDER'] = VOICES_DIRECTORY
app.config['ANIMATIONS_FOLDER'] = ANIMATIONS_DIRECTORY
app.config['MAX_AUDIO_FILES'] = 50
app.config['MAX_UPLOAD_SIZE'] = 50 * 1024 * 1024
app.config['ALLOWED_EXTENSIONS'] = {'wav', 'mp3', 'flac', 'ogg'}

# TTS Configuration
TTS_AVAILABLE = False
TTS_ENGINE = None
VOICE_CLONING_MODEL = None
DEVICE = "cuda" if torch.cuda.is_available() else "cpu"
BASE_MODEL = "tts_models/en/ljspeech/tacotron2-DDC"
VOICE_CLONING_MODEL_NAME = "tts_models/multilingual/multi-dataset/your_tts"

# Chatbot responses for TTS
CHATBOT_RESPONSES = {
    "greetings": [
        "Hello! I'm Sancia, your furry AI companion. How can I help you today?",
        "Hi there! Welcome to FurryChat.ai. What would you like to know?",
        "Greetings! I'm Sancia, ready to help you with all things furry AI.",
        "Welcome to FurryChat.ai! I'm here to make your experience enjoyable."
    ],
    "questions": {
        "what can you do": "I can chat with you about furry AI topics, explain our platform, and help you understand the benefits of signing up!",
        "how does this work": "I use AI to understand your messages and respond. You can also hear my responses with text-to-speech!",
        "who made you": "I was created by the team at FurryChat.ai to provide the perfect AI furry roleplay entertainment.",
        "what is tts": "TTS stands for Text-to-Speech. It converts written text into spoken words so you can hear my responses.",
        "what is coqui tts": "Coqui TTS is an advanced open-source text-to-speech system that supports many voices and languages.",
        "can you help me": "Of course! I can answer questions about FurryChat.ai, furry AI characters, or help you with anything else!",
        "tell me a joke": "Why don't scientists trust atoms? Because they make up everything!",
        "weather": "I don't have access to real-time weather data, but I hope it's pleasant where you are!",
        "time": f"I don't know the exact time, but it's currently {datetime.now().strftime('%I:%M %p')} on my server.",
        "help": "I can help you learn about FurryChat.ai, explain furry AI concepts, or chat with you about anything!",
        "voices": "You can use different voice styles for my responses. Some are pre-made, and you can even create custom ones!",
        "voice cloning": "Voice cloning allows the TTS system to mimic specific voices using audio samples.",
        "thank you": "You're welcome! I'm happy to help. Feel free to ask me anything else about FurryChat.ai.",
        "hello": "Hello again! How can I assist you today?",
        "hi": "Hi there! What would you like to know about furry AI?",
        "bye": "Goodbye! Remember to check out FurryChat.ai for more amazing furry AI experiences!"
    },
    "fallback": [
        "That's interesting! Could you tell me more about what you're looking for?",
        "I'm here to help you understand FurryChat.ai better. Could you rephrase your question?",
        "That's a great point! Would you like to know more about our community-made AI furries?",
        "I'm here to help with all things furry AI. Ask me about voice synthesis or our platform!",
        "Let me think about that. In the meantime, have you considered signing up for FurryChat.ai?",
        "I'm learning more about your question. Could you be more specific about what you'd like to know?",
        "That's a good question about furry AI! Let me help you with that.",
        "I appreciate your message. How can I assist you further with FurryChat.ai?"
    ]
}

def allowed_file(filename):
    return '.' in filename and filename.rsplit('.', 1)[1].lower() in app.config['ALLOWED_EXTENSIONS']

def analyze_glb_file(filepath):
    """Analyze GLB file structure to check for animations"""
    try:
        with open(filepath, 'rb') as f:
            # Read GLB header (12 bytes)
            magic = f.read(4)
            version = struct.unpack('<I', f.read(4))[0]
            length = struct.unpack('<I', f.read(4))[0]
            
            print(f"πŸ“Š Analyzing GLB: {os.path.basename(filepath)}")
            print(f"   Magic: {magic.hex()} ({magic})")
            print(f"   Version: {version}")
            print(f"   Length: {length} bytes")
            print(f"   File size: {os.path.getsize(filepath)} bytes")
            
            # Read chunks
            chunks = []
            has_animations = False
            animation_count = 0
            
            while f.tell() < length:
                chunk_length = struct.unpack('<I', f.read(4))[0]
                chunk_type = f.read(4)
                chunk_data = f.read(chunk_length)
                chunks.append((chunk_type, chunk_length))
                
                if chunk_type == b'JSON':
                    # Try to read JSON data
                    try:
                        import json
                        json_str = chunk_data.decode('utf-8', errors='ignore')
                        # Look for animations in JSON
                        if '"animations"' in json_str:
                            has_animations = True
                            # Count animations
                            animation_count = json_str.count('"name"')
                            print(f"   βœ… Found animations in JSON chunk")
                            print(f"   πŸ“ JSON preview: {json_str[:200]}...")
                    except Exception as json_error:
                        print(f"   ⚠ JSON parse error: {json_error}")
                
                f.read(4)  # Skip padding
            
            print(f"   Total chunks: {len(chunks)}")
            print(f"   Has animations: {has_animations}")
            if has_animations:
                print(f"   Estimated animations: {animation_count}")
            
            return has_animations
            
    except Exception as e:
        print(f"❌ Error analyzing GLB: {str(e)}")
        traceback.print_exc()
        return False

def check_animation_files():
    """Check if animation files exist and analyze them"""
    print(f"πŸ” Checking animation files in: {ANIMATIONS_DIRECTORY}")
    
    for model_name, filename in DEFAULT_ANIMATIONS.items():
        model_path = os.path.join(ANIMATIONS_DIRECTORY, filename)
        
        if os.path.exists(model_path):
            file_size = os.path.getsize(model_path)
            print(f"βœ… {filename}: Found ({file_size:,} bytes)")
            
            # Analyze the GLB file
            has_animations = analyze_glb_file(model_path)
            
            if not has_animations:
                print(f"⚠ {filename}: No animations detected - might be static model")
        else:
            print(f"❌ {filename}: NOT FOUND")
            print(f"   Expected at: {model_path}")

class TTSGenerator:
    def __init__(self):
        self.model = None
        self.voice_cloning_model = None
        self.device = DEVICE
        self.base_model = BASE_MODEL
        self.voice_cloning_model_name = VOICE_CLONING_MODEL_NAME
        self.available_voices = {}
        self.failure_count = {}
        self.max_failures = 3
        self.has_sancia_voice = False
        
        self.load_available_voices()
    
    def load_available_voices(self):
        """Load available voice samples from voice folder"""
        voice_dir = Path(app.config['VOICE_FOLDER'])
        if voice_dir.exists():
            for voice_file in voice_dir.glob("*.*"):
                if voice_file.suffix.lower()[1:] in app.config['ALLOWED_EXTENSIONS']:
                    voice_name = voice_file.stem
                    self.available_voices[voice_name] = str(voice_file)
        
        # Check if Sancia voice exists
        self.has_sancia_voice = DEFAULT_VOICE_NAME in self.available_voices
        if self.has_sancia_voice:
            print(f"βœ… Found Sancia voice: {DEFAULT_VOICE_FILE}")
        else:
            print(f"⚠ Sancia voice not found: {DEFAULT_VOICE_FILE}")
    
    def initialize_base_tts(self):
        """Initialize base TTS model"""
        try:
            self.model = TTS(self.base_model, gpu=(self.device == "cuda"))
            print(f"βœ… Base TTS model initialized: {self.base_model}")
            return True
        except Exception as e:
            print(f"❌ Failed to initialize base TTS: {str(e)}")
            return False
    
    def initialize_voice_cloning_tts(self):
        """Initialize voice cloning TTS model"""
        try:
            self.voice_cloning_model = TTS(self.voice_cloning_model_name, gpu=(self.device == "cuda"))
            print(f"βœ… Voice cloning TTS model initialized: {self.voice_cloning_model_name}")
            return True
        except Exception as e:
            print(f"⚠ Voice cloning TTS initialization failed: {str(e)}")
            return False
    
    def generate_base_speech(self, text, filename):
        """Generate speech using base TTS model (original voice)"""
        if not self.model:
            if not self.initialize_base_tts():
                return False
        
        try:
            output_path = os.path.join(app.config['AUDIO_FOLDER'], filename)
            print(f"🎡 Generating base speech (original voice): {filename[:20]}...")
            self.model.tts_to_file(text=text, file_path=output_path)
            
            if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
                print(f"βœ… Base speech generated: {filename}")
                return True
            else:
                print(f"❌ Base speech file too small or missing: {output_path}")
                return False
        except Exception as e:
            print(f"❌ Base TTS generation failed: {str(e)}")
            return False
    
    def generate_sancia_speech(self, text, filename):
        """Generate speech using Sancia voice (voice cloning)"""
        if not self.voice_cloning_model:
            if not self.initialize_voice_cloning_tts():
                print("❌ Voice cloning model not available, falling back to base TTS")
                return self.generate_base_speech(text, filename)
        
        if not self.has_sancia_voice:
            print("❌ Sancia voice not available, falling back to base TTS")
            return self.generate_base_speech(text, filename)
        
        try:
            output_path = os.path.join(app.config['AUDIO_FOLDER'], filename)
            print(f"🎡 Generating Sancia voice speech: {filename[:20]}...")
            
            self.voice_cloning_model.tts_to_file(
                text=text,
                speaker_wav=self.available_voices[DEFAULT_VOICE_NAME],
                file_path=output_path,
                language="en"
            )
            
            if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
                print(f"βœ… Sancia voice speech generated: {filename}")
                return True
            else:
                print(f"❌ Sancia voice speech file too small, falling back to base TTS")
                return self.generate_base_speech(text, filename)
        except Exception as e:
            print(f"❌ Sancia voice TTS generation failed, falling back to base: {str(e)}")
            return self.generate_base_speech(text, filename)
    
    def generate_voice_cloned_speech(self, text, filename, speaker_wav):
        """Generate speech using voice cloning model for custom voices"""
        if not self.voice_cloning_model:
            if not self.initialize_voice_cloning_tts():
                return False
        
        try:
            output_path = os.path.join(app.config['AUDIO_FOLDER'], filename)
            print(f"🎡 Generating voice cloned speech: {filename[:20]}...")
            self.voice_cloning_model.tts_to_file(
                text=text,
                speaker_wav=speaker_wav,
                file_path=output_path,
                language="en"
            )
            
            if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
                print(f"βœ… Voice cloned speech generated: {filename}")
                return True
            else:
                print(f"❌ Voice cloned speech file too small or missing: {output_path}")
                return False
        except Exception as e:
            print(f"❌ Voice cloning TTS generation failed: {str(e)}")
            return False
    
    def generate_speech_with_voice(self, text, filename, voice_name='default'):
        """Generate speech with specified voice"""
        print(f"πŸ”Š Generating speech with voice: '{voice_name}'")
        
        # Default voice (Sancia)
        if voice_name == 'default':
            if self.has_sancia_voice:
                return self.generate_sancia_speech(text, filename)
            else:
                print("⚠ Sancia voice not found, using original voice")
                return self.generate_base_speech(text, filename)
        
        # Original voice (base TTS)
        elif voice_name == 'original':
            return self.generate_base_speech(text, filename)
        
        # Custom voice
        elif voice_name in self.available_voices:
            return self.generate_voice_cloned_speech(text, filename, self.available_voices[voice_name])
        
        # Voice not found
        else:
            print(f"⚠ Voice '{voice_name}' not found, using default (Sancia)")
            if self.has_sancia_voice:
                return self.generate_sancia_speech(text, filename)
            else:
                return self.generate_base_speech(text, filename)
    
    def generate_chat_tts(self, text, voice_name='default'):
        """Generate TTS for chat messages"""
        if not text:
            return None
        
        # Generate unique filename
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        random_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
        filename = f"chat_{voice_name}_{timestamp}_{random_suffix}.wav"
        
        print(f"🎡 Generating chat TTS with voice '{voice_name}': {filename}")
        
        success = self.generate_speech_with_voice(text, filename, voice_name)
        
        if success:
            # Clean up old files occasionally
            if random.random() < 0.1:
                self.cleanup_old_files()
            return filename
        
        return None
    
    def generate_welcome_tts(self, voice_name='default'):
        """Generate TTS specifically for welcome message"""
        print(f"🎡 Generating welcome message TTS with voice '{voice_name}'...")
        
        # Use a fixed filename for welcome message based on voice
        if voice_name == 'default':
            welcome_filename = "welcome_sancia.wav"
        elif voice_name == 'original':
            welcome_filename = "welcome_original.wav"
        else:
            welcome_filename = f"welcome_{voice_name}.wav"
        
        output_path = os.path.join(app.config['AUDIO_FOLDER'], welcome_filename)
        
        # Check if welcome TTS already exists and is valid
        if os.path.exists(output_path) and os.path.getsize(output_path) > 1000:
            print(f"βœ… Welcome TTS already exists: {welcome_filename}")
            return welcome_filename
        
        # Generate new welcome TTS with specified voice
        success = self.generate_speech_with_voice(WELCOME_MESSAGE, welcome_filename, voice_name)
        
        if success:
            print(f"βœ… Welcome TTS generated: {welcome_filename}")
            return welcome_filename
        else:
            print(f"❌ Failed to generate welcome TTS with voice '{voice_name}'")
            return None
    
    def process_uploaded_voice(self, audio_file, voice_name):
        """Process and save uploaded voice sample"""
        try:
            audio, sr = librosa.load(audio_file, sr=22050)
            audio_trimmed, _ = librosa.effects.trim(audio, top_db=20)
            
            min_samples = int(sr * 5)
            if len(audio_trimmed) < min_samples:
                padding = min_samples - len(audio_trimmed)
                audio_trimmed = np.pad(audio_trimmed, (0, padding), mode='constant')
            
            output_path = os.path.join(app.config['VOICE_FOLDER'], f"{voice_name}.wav")
            sf.write(output_path, audio_trimmed, sr)
            
            self.available_voices[voice_name] = output_path
            
            metadata = {
                "name": voice_name,
                "sample_rate": sr,
                "duration": len(audio_trimmed) / sr,
                "file_size": os.path.getsize(output_path),
                "created_at": datetime.now().isoformat()
            }
            
            with open(os.path.join(app.config['VOICE_FOLDER'], f"{voice_name}.json"), "w") as f:
                json.dump(metadata, f, indent=2)
            
            return True
            
        except Exception as e:
            print(f"❌ Failed to process voice sample: {str(e)}")
            return False
    
    def get_voice_preview(self, voice_name, text="Hello, this is a test of the voice."):
        """Generate a preview for a voice"""
        if voice_name not in self.available_voices:
            return None
        
        preview_filename = f"preview_{voice_name}_{datetime.now().strftime('%H%M%S')}.wav"
        
        success = self.generate_voice_cloned_speech(
            text=text,
            filename=preview_filename,
            speaker_wav=self.available_voices[voice_name]
        )
        
        if success:
            return preview_filename
        
        return None
    
    def cleanup_old_files(self):
        """Clean up old audio files"""
        audio_dir = Path(app.config['AUDIO_FOLDER'])
        audio_files = list(audio_dir.glob("*.wav"))
        
        if len(audio_files) > app.config['MAX_AUDIO_FILES']:
            audio_files.sort(key=lambda x: x.stat().st_ctime)
            files_to_remove = len(audio_files) - app.config['MAX_AUDIO_FILES']
            for i in range(files_to_remove):
                try:
                    audio_files[i].unlink()
                except:
                    pass

class Chatbot:
    def __init__(self):
        self.conversation_history = []
        self.greeting_sent = False
        
    def get_greeting(self):
        """Get chatbot greeting message"""
        import random
        greeting = random.choice(CHATBOT_RESPONSES["greetings"])
        return greeting
    
    def get_response(self, user_message):
        """Get chatbot response to user message"""
        user_message_lower = user_message.lower().strip()
        
        # Check for specific questions
        response = None
        for key, answer in CHATBOT_RESPONSES["questions"].items():
            if key in user_message_lower:
                response = answer
                break
        
        # If no specific match, use fallback
        if not response:
            import random
            response = random.choice(CHATBOT_RESPONSES["fallback"])
        
        return response

# Initialize TTS generator and chatbot
tts_generator = TTSGenerator()
chatbot = Chatbot()

def get_personalized_response(user_message, conversation_history):
    """Get AI response"""
    try:
        from Deepseek import get_deepseek_response
        
        enhanced_prompt = f"""
        {CHARACTER_DEFINITION}
        
        Current user message: {user_message}
        
        Please respond as Sancia, maintaining a friendly and helpful personality.
        """
        
        response = get_deepseek_response(enhanced_prompt, [])
        return response
        
    except Exception as e:
        print(f"❌ Error in get_personalized_response: {str(e)}")
        return "I'm having some technical difficulties right now."

# Initialize TTS on startup
def initialize_tts():
    global TTS_AVAILABLE
    try:
        print("πŸš€ Initializing TTS systems...")
        print(f"πŸ“ Looking for Sancia voice at: {DEFAULT_VOICE_PATH}")
        
        # Check if Sancia voice file exists
        if os.path.exists(DEFAULT_VOICE_PATH):
            print(f"βœ… Sancia voice file found: {DEFAULT_VOICE_FILE}")
        else:
            print(f"⚠ Sancia voice file NOT found: {DEFAULT_VOICE_FILE}")
            print(f"πŸ“ Voices directory contents: {os.listdir(VOICES_DIRECTORY) if os.path.exists(VOICES_DIRECTORY) else 'Directory not found'}")
        
        # Initialize base TTS first
        base_ready = tts_generator.initialize_base_tts()
        
        if base_ready:
            TTS_AVAILABLE = True
            print("βœ… Base TTS system initialized successfully")
            
            # Try to initialize voice cloning
            try:
                tts_generator.initialize_voice_cloning_tts()
            except Exception as e:
                print(f"⚠ Voice cloning optional, continuing without it: {e}")
            
            # Pre-generate welcome message with Sancia voice
            print("🎡 Pre-generating welcome message with Sancia voice...")
            welcome_file = tts_generator.generate_welcome_tts('default')
            if welcome_file:
                print(f"βœ… Sancia voice welcome TTS ready: {welcome_file}")
            else:
                print("⚠ Sancia voice welcome TTS generation failed")
            
            # Also pre-generate original voice welcome as fallback
            print("🎡 Pre-generating fallback welcome with original voice...")
            original_welcome = tts_generator.generate_welcome_tts('original')
            if original_welcome:
                print(f"βœ… Original voice welcome TTS ready: {original_welcome}")
            
            # Print available voices
            voice_count = len(tts_generator.available_voices)
            print(f"🎭 Found {voice_count} voice file(s) for cloning")
            if tts_generator.has_sancia_voice:
                print(f"βœ… Sancia voice available: {DEFAULT_VOICE_FILE}")
            else:
                print(f"❌ Sancia voice not available in loaded voices")
            
        else:
            print(f"❌ Base TTS initialization failed")
            TTS_AVAILABLE = False
        
        return TTS_AVAILABLE
        
    except Exception as e:
        print(f"❌ TTS initialization error: {str(e)}")
        traceback.print_exc()
        TTS_AVAILABLE = False
        return False

# ============================================================================
# MAIN APPLICATION ROUTES
# ============================================================================

@app.route('/')
def index():
    return render_template('index.html', welcome_message=WELCOME_MESSAGE)

@app.route('/api/welcome', methods=['GET'])
def get_welcome_message():
    """API endpoint to get the welcome message with TTS"""
    try:
        welcome_filename = None
        audio_url = None
        has_audio = False
        voice_used = 'default'
        
        print(f"🎯 Welcome endpoint called. TTS_AVAILABLE: {TTS_AVAILABLE}")
        
        # Check if TTS is available
        if TTS_AVAILABLE:
            try:
                # Try to get Sancia voice welcome TTS first
                welcome_filename = tts_generator.generate_welcome_tts('default')
                voice_used = 'Sancia'
                
                if not welcome_filename:
                    # Fall back to original voice
                    print("⚠ Sancia voice failed, trying original voice...")
                    welcome_filename = tts_generator.generate_welcome_tts('original')
                    voice_used = 'Original'
                
                if welcome_filename:
                    audio_url = f'/api/audio/{welcome_filename}'
                    has_audio = True
                    print(f"βœ… Welcome TTS available ({voice_used}): {welcome_filename}")
                else:
                    print("❌ All welcome TTS generation attempts failed")
                    
            except Exception as tts_error:
                print(f"❌ Welcome TTS generation exception: {tts_error}")
                traceback.print_exc()
        else:
            print(f"⚠ TTS not available for welcome message")
        
        print(f"πŸ“Š Returning welcome message. Voice: {voice_used}, Has audio: {has_audio}")
        
        return jsonify({
            'message': WELCOME_MESSAGE,
            'audio_url': audio_url,
            'audio_filename': welcome_filename,
            'has_audio': has_audio,
            'voice_used': voice_used,
            'status': 'success'
        })
        
    except Exception as e:
        print(f"❌ Error in get_welcome_message: {str(e)}")
        traceback.print_exc()
        return jsonify({
            'message': WELCOME_MESSAGE,
            'audio_url': None,
            'audio_filename': None,
            'has_audio': False,
            'voice_used': 'none',
            'status': 'success'
        })

@app.route('/api/model', methods=['GET'])
def get_model():
    """Get information about the current model"""
    try:
        if os.path.exists(MODEL_PATH):
            model_name = "Talking Animation" if SPECIFIC_MODEL == "talking.glb" else "Idle Animation"
            return jsonify({
                'model': {
                    'filename': SPECIFIC_MODEL, 
                    'name': model_name,
                    'type': 'animation' if SPECIFIC_MODEL.endswith('.glb') else 'static',
                    'has_animations': True if SPECIFIC_MODEL.endswith('.glb') else False
                },
                'status': 'success'
            })
        else:
            return jsonify({'error': f'Model not found: {MODEL_PATH}'}), 404
    except Exception as e:
        return jsonify({'error': 'Failed to fetch model'}), 500

@app.route('/api/model/file', methods=['GET'])
def serve_model():
    """Serve the main model file"""
    try:
        if not os.path.exists(MODEL_PATH):
            return jsonify({'error': f'Model file not found: {MODEL_PATH}'}), 404
        return send_file(MODEL_PATH, mimetype='model/gltf-binary')
    except Exception as e:
        print(f"❌ Error serving model: {str(e)}")
        return jsonify({'error': 'Failed to serve model'}), 500

@app.route('/api/audio/<filename>', methods=['GET'])
def serve_audio(filename):
    """Serve audio files"""
    try:
        filepath = os.path.join(app.config['AUDIO_FOLDER'], filename)
        
        if os.path.exists(filepath):
            return send_file(filepath, mimetype='audio/wav')
        else:
            return jsonify({'error': 'Audio file not found'}), 404
    except Exception as e:
        print(f"❌ Error serving audio: {str(e)}")
        return jsonify({'error': 'Failed to serve audio'}), 500

@app.route('/api/chat', methods=['POST', 'OPTIONS'])
def chat():
    try:
        if request.method == 'OPTIONS':
            return jsonify({'status': 'ok'}), 200
            
        data = request.get_json()
        if not data:
            return jsonify({'error': 'No JSON data provided'}), 400
            
        user_message = data.get('message')
        voice_name = data.get('voice', 'default')  # 'default' means Sancia voice
        
        if not user_message:
            return jsonify({'error': 'No message provided'}), 400
        
        print(f"πŸ’¬ Chat: '{user_message[:50]}...' with voice: {voice_name}")
        
        # Get AI response
        ai_response = get_personalized_response(user_message, [])
        
        # Generate TTS if available
        audio_filename = None
        audio_url = None
        
        if TTS_AVAILABLE:
            audio_filename = tts_generator.generate_chat_tts(ai_response, voice_name)
            if audio_filename:
                audio_url = f'/api/audio/{audio_filename}'
        
        return jsonify({
            'response': ai_response,
            'audio_url': audio_url,
            'audio_filename': audio_filename,
            'voice_used': voice_name,
            'status': 'success'
        })
        
    except Exception as e:
        print(f"❌ Error in chat endpoint: {str(e)}")
        traceback.print_exc()
        return jsonify({'error': 'Internal server error'}), 500

@app.route('/api/tts/generate', methods=['POST'])
def generate_speech():
    """Generate speech from text"""
    try:
        data = request.get_json()
        text = data.get('text', '')
        voice_name = data.get('voice_name', 'default')  # Default to Sancia voice
        
        if not text:
            return jsonify({'error': 'No text provided'}), 400
        
        if not TTS_AVAILABLE:
            return jsonify({'error': 'TTS not available'}), 503
        
        timestamp = datetime.now().strftime('%Y%m%d_%H%M%S')
        random_suffix = ''.join(random.choices(string.ascii_lowercase + string.digits, k=6))
        filename = f"speech_{voice_name}_{timestamp}_{random_suffix}.wav"
        
        success = tts_generator.generate_speech_with_voice(
            text=text,
            filename=filename,
            voice_name=voice_name
        )
        
        if success:
            tts_generator.cleanup_old_files()
            
            voice_used = 'Sancia' if voice_name == 'default' else voice_name
            
            return jsonify({
                'success': True,
                'audio_url': f'/api/audio/{filename}',
                'filename': filename,
                'voice_used': voice_used
            })
        else:
            return jsonify({
                'success': False,
                'error': 'Failed to generate speech'
            }), 500
            
    except Exception as e:
        print(f"❌ TTS generation error: {str(e)}")
        traceback.print_exc()
        return jsonify({'error': 'Failed to generate speech'}), 500

@app.route('/api/tts/voices', methods=['GET'])
def get_voices():
    """Get list of available voices"""
    try:
        voices_data = []
        
        # Add Sancia as default voice
        voices_data.append({
            'name': 'default',
            'display_name': '🎭 Sancia Voice (Default)',
            'type': 'default',
            'description': 'The main Sancia voice using voice cloning',
            'available': tts_generator.has_sancia_voice
        })
        
        # Add original voice as option
        voices_data.append({
            'name': 'original',
            'display_name': 'πŸ”Š Original TTS Voice',
            'type': 'base',
            'description': 'Standard TTS voice (fallback)',
            'available': True
        })
        
        # Add custom voices (excluding Sancia if it's already there)
        for voice_name, voice_path in tts_generator.available_voices.items():
            if voice_name != DEFAULT_VOICE_NAME:  # Don't add Sancia twice
                voice_info = {
                    'name': voice_name,
                    'display_name': f'🎀 {voice_name}',
                    'file_path': voice_path,
                    'preview_url': f'/api/voice-preview/{voice_name}',
                    'type': 'custom',
                    'available': True
                }
                
                # Add metadata if available
                metadata_path = voice_path.replace('.wav', '.json')
                if os.path.exists(metadata_path):
                    try:
                        with open(metadata_path, 'r') as f:
                            metadata = json.load(f)
                            voice_info.update(metadata)
                    except:
                        pass
                
                voices_data.append(voice_info)
        
        return jsonify({
            'voices': voices_data,
            'status': 'success',
            'tts_available': TTS_AVAILABLE,
            'has_sancia_voice': tts_generator.has_sancia_voice,
            'default_voice': DEFAULT_VOICE_NAME,
            'default_voice_available': tts_generator.has_sancia_voice
        })
    except Exception as e:
        print(f"❌ Error getting voices: {str(e)}")
        return jsonify({'error': 'Failed to get voices'}), 500

@app.route('/api/tts/info', methods=['GET'])
def tts_info():
    """Get TTS system information"""
    try:
        cache_files = list(Path(TTS_CACHE_DIR).glob("*.wav"))
        cache_size = sum(f.stat().st_size for f in cache_files if f.is_file())
        voices = len(tts_generator.available_voices)
        
        # Check audio folder for existing files
        audio_files = list(Path(app.config['AUDIO_FOLDER']).glob("*.wav"))
        welcome_sancia_exists = os.path.exists(os.path.join(app.config['AUDIO_FOLDER'], 'welcome_sancia.wav'))
        welcome_original_exists = os.path.exists(os.path.join(app.config['AUDIO_FOLDER'], 'welcome_original.wav'))
        
        return jsonify({
            'status': 'ready' if TTS_AVAILABLE else 'not_available',
            'tts_engine': 'coqui_tts',
            'tts_available': TTS_AVAILABLE,
            'voice_cloning': True,
            'voices_available': voices,
            'device': tts_generator.device,
            'base_model': tts_generator.base_model,
            'cloning_model': tts_generator.voice_cloning_model_name,
            'has_sancia_voice': tts_generator.has_sancia_voice,
            'default_voice': DEFAULT_VOICE_NAME,
            'welcome_sancia_ready': welcome_sancia_exists,
            'welcome_original_ready': welcome_original_exists,
            'cache_enabled': True,
            'cache_size': len(cache_files),
            'cache_mb': round(cache_size / (1024 * 1024), 2) if cache_size > 0 else 0,
            'audio_files': len(audio_files),
            'message': 'Enhanced TTS with Sancia as default voice'
        })
    except Exception as e:
        print(f"❌ Error getting TTS info: {str(e)}")
        return jsonify({'error': 'Failed to get TTS info'}), 500

@app.route('/api/voice-preview/<voice_name>', methods=['GET'])
def api_generate_voice_preview(voice_name):
    """Generate and return a voice preview"""
    try:
        if voice_name == 'default':
            # Generate Sancia voice preview
            preview_text = "Hello, this is the Sancia voice. How do I sound?"
            preview_filename = tts_generator.generate_chat_tts(preview_text, 'default')
        elif voice_name == 'original':
            # Generate original voice preview
            preview_text = "Hello, this is the original TTS voice. How do I sound?"
            preview_filename = tts_generator.generate_chat_tts(preview_text, 'original')
        else:
            # Generate custom voice preview
            if voice_name not in tts_generator.available_voices:
                return jsonify({'error': 'Voice not found'}), 404
            
            preview_text = "Hello, this is a preview of this custom voice. How do I sound?"
            preview_filename = tts_generator.get_voice_preview(voice_name, preview_text)
        
        if preview_filename:
            return jsonify({
                'success': True,
                'audio_url': f'/api/audio/{preview_filename}',
                'filename': preview_filename
            })
        else:
            return jsonify({'error': 'Failed to generate preview'}), 500
    except Exception as e:
        print(f"❌ Error generating voice preview: {str(e)}")
        return jsonify({'error': 'Failed to generate preview'}), 500

@app.route('/api/upload-voice', methods=['POST'])
def api_upload_voice():
    """Upload a new voice sample"""
    if 'voice_file' not in request.files:
        return jsonify({'error': 'No file provided'}), 400
    
    file = request.files['voice_file']
    voice_name = request.form.get('voice_name', '').strip()
    
    if not voice_name:
        return jsonify({'error': 'Voice name is required'}), 400
    
    if file.filename == '':
        return jsonify({'error': 'No file selected'}), 400
    
    if not allowed_file(file.filename):
        return jsonify({'error': 'File type not allowed'}), 400
    
    file.seek(0, os.SEEK_END)
    file_length = file.tell()
    file.seek(0)
    
    if file_length > app.config['MAX_UPLOAD_SIZE']:
        return jsonify({'error': 'File too large'}), 400
    
    if voice_name in tts_generator.available_voices:
        return jsonify({'error': 'Voice name already exists'}), 400
    
    success = tts_generator.process_uploaded_voice(file, voice_name)
    
    if success:
        return jsonify({
            'success': True,
            'message': 'Voice uploaded successfully',
            'voice_name': voice_name
        })
    else:
        return jsonify({'error': 'Failed to process voice sample'}), 500

# ============================================================================
# ANIMATION SYSTEM ROUTES (From Plan C)
# ============================================================================

@app.route('/animations')
def animations_page():
    """Serve the animations test page"""
    return render_template('test_animations.html')

@app.route('/api/animations/status')
def animations_status():
    """API endpoint to check animations backend status"""
    return jsonify({
        "status": "running",
        "models_available": list(DEFAULT_ANIMATIONS.keys()),
        "animations_directory": ANIMATIONS_DIRECTORY,
        "current_main_model": SPECIFIC_MODEL
    })

@app.route('/api/animations/model/<model_name>')
def get_animation_model(model_name):
    """API endpoint to retrieve 3D animation model files"""
    if model_name not in DEFAULT_ANIMATIONS:
        return jsonify({"error": f"Model '{model_name}' not found"}), 404
    
    filename = DEFAULT_ANIMATIONS[model_name]
    model_path = os.path.join(app.config['ANIMATIONS_FOLDER'], filename)
    
    if not os.path.exists(model_path):
        return jsonify({"error": f"Model file '{filename}' not found at {model_path}"}), 404
    
    print(f"Serving animation model: {filename}")
    return send_file(model_path, mimetype='model/gltf-binary')

@app.route('/animations/<path:filename>')
def serve_animation_file(filename):
    """Serve files directly from the animations directory"""
    return send_from_directory(app.config['ANIMATIONS_FOLDER'], filename)

# ============================================================================
# ANIMATION CONTROL API
# ============================================================================

@app.route('/api/animation/switch/<animation_name>', methods=['POST'])
def switch_animation(animation_name):
    """Switch the current animation"""
    global SPECIFIC_MODEL, MODEL_PATH
    
    if animation_name not in DEFAULT_ANIMATIONS:
        return jsonify({'error': f'Animation {animation_name} not found'}), 404
    
    new_model = DEFAULT_ANIMATIONS[animation_name]
    new_model_path = os.path.join(ANIMATIONS_DIRECTORY, new_model)
    
    if not os.path.exists(new_model_path):
        return jsonify({'error': f'Animation file not found: {new_model_path}'}), 404
    
    # Update the current model
    SPECIFIC_MODEL = new_model
    MODEL_PATH = new_model_path
    
    print(f"πŸ”„ Switched to animation: {animation_name} ({new_model})")
    
    return jsonify({
        'success': True,
        'message': f'Switched to {animation_name} animation',
        'animation': animation_name,
        'model_file': new_model,
        'model_path': new_model_path
    })

@app.route('/api/animation/current', methods=['GET'])
def get_current_animation():
    """Get the current animation state"""
    animation_name = None
    for name, filename in DEFAULT_ANIMATIONS.items():
        if filename == SPECIFIC_MODEL:
            animation_name = name
            break
    
    return jsonify({
        'current_animation': animation_name or 'unknown',
        'model_file': SPECIFIC_MODEL,
        'model_path': MODEL_PATH,
        'available_animations': list(DEFAULT_ANIMATIONS.keys())
    })

# ============================================================================
# TESTING AND HEALTH ENDPOINTS
# ============================================================================

@app.route('/api/test', methods=['GET'])
def test_api():
    return jsonify({
        'status': 'success',
        'message': 'API working',
        'tts_engine': 'coqui_tts',
        'tts_available': TTS_AVAILABLE,
        'device': tts_generator.device,
        'has_sancia_voice': tts_generator.has_sancia_voice,
        'animations_available': True,
        'animations_count': len(DEFAULT_ANIMATIONS),
        'current_model': SPECIFIC_MODEL,
        'model_path': MODEL_PATH
    })

@app.route('/api/health', methods=['GET'])
def health_check():
    # Determine current animation name
    current_animation = None
    for name, filename in DEFAULT_ANIMATIONS.items():
        if filename == SPECIFIC_MODEL:
            current_animation = name
            break
    
    return jsonify({
        'status': 'healthy',
        'service': 'FurryChat.ai',
        'tts_engine': 'coqui_tts',
        'voice_cloning': True,
        'tts_available': TTS_AVAILABLE,
        'default_voice': DEFAULT_VOICE_NAME,
        'has_sancia_voice': tts_generator.has_sancia_voice,
        'animations_system': 'ready',
        'animations_available': list(DEFAULT_ANIMATIONS.keys()),
        'current_animation': current_animation,
        'current_model': SPECIFIC_MODEL
    })

# ============================================================================
# ERROR HANDLERS
# ============================================================================

@app.errorhandler(404)
def not_found(error):
    return jsonify({"error": "Endpoint not found"}), 404

@app.errorhandler(500)
def internal_error(error):
    return jsonify({"error": "Internal server error"}), 500

# ============================================================================
# MAIN APPLICATION STARTUP
# ============================================================================

if __name__ == '__main__':
    print("=" * 60)
    print("πŸš€ Starting FurryChat.ai with Integrated Animations System")
    print("=" * 60)
    
    # Check 3D model
    if os.path.exists(MODEL_PATH):
        print(f"βœ… 3D Main Model: {SPECIFIC_MODEL}")
        print(f"   Path: {MODEL_PATH}")
        print(f"   Size: {os.path.getsize(MODEL_PATH):,} bytes")
    else:
        print(f"❌ 3D Main Model not found: {MODEL_PATH}")
        # Try to find it
        if os.path.exists(ANIMATIONS_DIRECTORY):
            files = os.listdir(ANIMATIONS_DIRECTORY)
            print(f"   Available files: {files}")
            # Try to use the first GLB file
            for file in files:
                if file.endswith('.glb'):
                    SPECIFIC_MODEL = file
                    MODEL_PATH = os.path.join(ANIMATIONS_DIRECTORY, file)
                    print(f"   Using alternative: {file}")
                    break
    
    # Check animation models
    check_animation_files()
    
    # Check Sancia voice file
    if os.path.exists(DEFAULT_VOICE_PATH):
        print(f"βœ… Sancia Voice: {DEFAULT_VOICE_FILE} (Found)")
    else:
        print(f"⚠ Sancia Voice: {DEFAULT_VOICE_FILE} (Not found - will use original voice)")
        print(f"πŸ“ Please ensure {DEFAULT_VOICE_FILE} is in {VOICES_DIRECTORY}")
    
    # Initialize TTS FIRST (before any requests)
    if initialize_tts():
        print("βœ… TTS: Ready with Sancia as default voice")
        print(f"πŸ“¦ Audio Output: {AUDIO_OUTPUT_DIR}")
        print(f"🎭 Voice Files: {VOICES_DIRECTORY}")
    else:
        print("❌ TTS: Initialization failed")
        print("πŸ’‘ To install TTS: pip install coqui-tts torch torchaudio")
    
    print(f"🎬 Animations System: Ready")
    print(f"   - Current animation: {SPECIFIC_MODEL}")
    print(f"   - Access test at: http://127.0.0.1:5000/animations")
    print(f"   - Switch API: POST /api/animation/switch/<idle|talking>")
    
    print(f"🌐 Main Interface: http://127.0.0.1:5000")
    print("=" * 60)
    
    app.run(debug=True, port=5000, host='0.0.0.0', threaded=True)