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e683b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c17d49e
 
 
 
 
 
 
 
 
 
 
2fe683b
c17d49e
2fe683b
 
75136b3
2fe683b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
8e5e32f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2fe683b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
from flask import Flask, request, jsonify, send_from_directory
from flask_cors import CORS
from flask_sock import Sock
import google.generativeai as genai
import os
import json
from datetime import datetime
import logging
import asyncio
import threading
from io import BytesIO
import numpy as np
import pickle
import re
from config import GEMINI_API_KEY, SERVER_IP, SERVER_PORT
from config import GCP_SERVICE_ACCOUNT_FILE, SPEECH_LANGUAGE_CODE
from config import DB_CONFIG, ENABLE_FLASK_DB
from text_utils import clean_text
import sys

# HACK: Inject clean_text into the __main__ module. 
# Pickled models saved in a notebook often expect to find functions in '__main__'.
# When running with gunicorn, __main__ is gunicorn, so we must manually inject it.
import __main__
__main__.clean_text = clean_text
# Also inject into this module's name for extra safety
sys.modules['app'].clean_text = clean_text

# MySQL database imports
try:
    import mysql.connector
    from mysql.connector import Error as MySQLError
    _mysql_available = True
except Exception:
    _mysql_available = False
    logging.warning("MySQL connector not available")

# Emotion detection imports
try:
    import cv2
    from fer import FER
    _emotion_detection_available = True
except Exception as e:
    _emotion_detection_available = False
    logging.warning(f"Emotion detection not available: {e}")

# Google Cloud Speech-to-Text
try:
    from google.oauth2 import service_account
    from google.cloud import speech
    _speech_available = True
except Exception:
    _speech_available = False

# GCP Credentials - Support both file and environment variable (for Hugging Face Spaces)
_gcp_credentials = None
if _speech_available:
    # Try environment variable first (Hugging Face Spaces secret)
    gcp_json_str = os.environ.get('GCP_CREDENTIALS_JSON')
    if gcp_json_str:
        try:
            import json as json_module
            gcp_info = json_module.loads(gcp_json_str)
            _gcp_credentials = service_account.Credentials.from_service_account_info(gcp_info)
            logging.info("GCP credentials loaded from GCP_CREDENTIALS_JSON environment variable")
        except Exception as e:
            logging.warning(f"Failed to parse GCP_CREDENTIALS_JSON: {e}")
    # Fallback to file if env var not available
    elif GCP_SERVICE_ACCOUNT_FILE and os.path.exists(GCP_SERVICE_ACCOUNT_FILE):
        try:
            _gcp_credentials = service_account.Credentials.from_service_account_file(GCP_SERVICE_ACCOUNT_FILE)
            logging.info(f"GCP credentials loaded from file: {GCP_SERVICE_ACCOUNT_FILE}")
        except Exception as e:
            logging.warning(f"Failed to load GCP credentials from file: {e}")
    
    if _gcp_credentials is None:
        _speech_available = False
        logging.warning("Speech-to-Text: No GCP credentials available")

# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

app = Flask(__name__)
CORS(app)  # Enable CORS for Flutter app
sock = Sock(app)  # Enable WebSocket support

# Configure Gemini AI
genai.configure(api_key=GEMINI_API_KEY)

# Initialize Gemini model
model = genai.GenerativeModel('gemini-2.5-flash')

# Store conversation sessions in memory (in production, use a database)
conversation_sessions = {}
stt_sessions = {}

class ConversationSession:
    def __init__(self, session_id):
        self.session_id = session_id
        self.messages = []
        self.question_count = 0
        self.user_emotions = []
        self.conversation_complete = False
        self.created_at = datetime.now()
        
    def add_message(self, message, is_user=True, emotion=None):
        self.messages.append({
            'text': message,
            'is_user': is_user,
            'timestamp': datetime.now().isoformat(),
            'emotion': emotion
        })
        
        if is_user and emotion:
            self.user_emotions.append(emotion)
    
    def get_conversation_context(self):
        context = "You are an empathetic AI companion helping someone journal their feelings and daily experiences. "
        context += "Your goal is to help the user express their feelings and understand what they did today through gentle, follow-up questions. "
        context += "Be supportive, understanding, and ask one thoughtful question at a time. "
        context += "Keep responses concise (2-3 sentences max). "
        context += "Continue the conversation naturally based on what the user shares - don't impose artificial limits. "
        context += "Let the user guide when they're ready to finish by listening for closing cues in their responses. "
        
        # Add recent conversation history
        if self.messages:
            context += "\n\nConversation so far:\n"
            for msg in self.messages[-8:]:  # Last 8 messages for context
                role = "User" if msg['is_user'] else "AI"
                context += f"{role}: {msg['text']}\n"
        
        return context

class STTSession:
    def __init__(self, session_id):
        self.session_id = session_id
        self.audio_buffer = BytesIO()
        self.is_recording = False
        self.created_at = datetime.now()

# ============================================================================
# EMOTION DETECTION CLASS
# ============================================================================

class EmotionDetectionBridge:
    """Emotion detection using FER (Facial Emotion Recognition)"""

    def __init__(self):
        self.emotion_detector = None
        self.face_cascade = None
        self.is_initialized = False
        self.current_emotion_data = {
            'dominant_emotion': 'neutral',
            'confidence': 0.0,
            'all_emotions': {},
            'timestamp': datetime.now().isoformat(),
            'face_detected': False
        }

    def initialize(self):
        """Initialize emotion detection system"""
        try:
            if not _emotion_detection_available:
                logger.warning("Emotion detection dependencies not available")
                return False

            # Initialize FER emotion detector without MTCNN (use OpenCV instead)
            # MTCNN has TorchVision issues, so we use OpenCV's haarcascade
            self.emotion_detector = FER(mtcnn=False)

            # Load face cascade classifier from backend folder
            cascade_path = os.path.join(
                os.path.dirname(__file__),
                'haarcascade_frontalface_default.xml'
            )

            if os.path.exists(cascade_path):
                self.face_cascade = cv2.CascadeClassifier(cascade_path)
                logger.info(f"Loaded cascade from: {cascade_path}")
            else:
                # Fallback to OpenCV's built-in cascade
                logger.warning(f"Cascade not found at {cascade_path}, using built-in")
                self.face_cascade = cv2.CascadeClassifier(
                    cv2.data.haarcascades + 'haarcascade_frontalface_default.xml'
                )

            self.is_initialized = True
            logger.info("Emotion detection system initialized successfully")
            return True

        except Exception as e:
            logger.error(f"Error initializing emotion detection: {e}")
            return False

    def detect_emotion_from_frame(self, frame_data):
        """Detect emotion from camera frame using cascade + FER"""
        try:
            if not self.is_initialized:
                return self.get_neutral_emotion()

            # Convert frame_data to numpy array if needed
            if isinstance(frame_data, bytes):
                nparr = np.frombuffer(frame_data, np.uint8)
                frame = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
            else:
                frame = frame_data

            if frame is None:
                return self.get_neutral_emotion()

            # Convert to grayscale for cascade detection
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

            # Detect faces using Haar Cascade
            faces = self.face_cascade.detectMultiScale(
                gray,
                scaleFactor=1.1,
                minNeighbors=5,
                minSize=(30, 30)
            )

            # Only proceed if cascade detected at least one face
            if len(faces) == 0:
                # No face detected by cascade
                logger.info(">> [FER] Cascade: NO FACE DETECTED")
                self.current_emotion_data = self.get_neutral_emotion()
                self.current_emotion_data['face_detected'] = False
                self.current_emotion_data['face_box'] = None
                return self.current_emotion_data

            # Get the first (largest) face detected by cascade
            (x, y, w, h) = faces[0]
            logger.info(f">> [FER] Cascade: FACE DETECTED at ({x}, {y}) size {w}x{h}")

            # Now detect emotions using FER on the frame
            emotions = self.emotion_detector.detect_emotions(frame)
            logger.info(f">> [FER] FER returned: {len(emotions) if emotions else 0} emotion(s)")

            if emotions and len(emotions) > 0:
                # Get the first (most prominent) face emotion
                emotion_data = emotions[0]
                all_emotions_raw = emotion_data["emotions"]
                logger.info(f">> [FER] RAW emotions: {all_emotions_raw}")

                # Filter to only include angry, sad, fear, neutral
                target_emotions = ['angry', 'sad', 'fear', 'neutral']
                filtered_emotions = {
                    emotion: all_emotions_raw.get(emotion, 0.0)
                    for emotion in target_emotions
                }
                logger.info(f">> [FER] FILTERED emotions (before normalize): {filtered_emotions}")

                # Normalize the filtered emotions to sum to 1.0
                total = sum(filtered_emotions.values())
                if total > 0:
                    filtered_emotions = {
                        k: v / total for k, v in filtered_emotions.items()
                    }
                logger.info(f">> [FER] NORMALIZED emotions: {filtered_emotions}")

                # Find dominant emotion from filtered set
                dominant_emotion = max(filtered_emotions, key=filtered_emotions.get)
                confidence = filtered_emotions[dominant_emotion]
                logger.info(f">> [FER] DOMINANT: {dominant_emotion} ({confidence*100:.1f}%)")

                self.current_emotion_data = {
                    'dominant_emotion': dominant_emotion,
                    'confidence': float(confidence),
                    'all_emotions': {k: float(v) for k, v in filtered_emotions.items()},
                    'timestamp': datetime.now().isoformat(),
                    'face_detected': True,
                    'face_box': {
                        'x': int(x),
                        'y': int(y),
                        'width': int(w),
                        'height': int(h)
                    }
                }
            else:
                # Cascade detected face but FER didn't - still return face box
                self.current_emotion_data = self.get_neutral_emotion()
                self.current_emotion_data['face_detected'] = True
                self.current_emotion_data['face_box'] = {
                    'x': int(x),
                    'y': int(y),
                    'width': int(w),
                    'height': int(h)
                }

            return self.current_emotion_data

        except Exception as e:
            logger.error(f"Error detecting emotion: {e}")
            return self.get_neutral_emotion()

    def get_neutral_emotion(self):
        """Return neutral emotion data"""
        return {
            'dominant_emotion': 'neutral',
            'confidence': 1.0,
            'all_emotions': {
                'angry': 0.0,
                'sad': 0.0,
                'fear': 0.0,
                'neutral': 1.0
            },
            'timestamp': datetime.now().isoformat(),
            'face_detected': False,
            'face_box': None
        }

# Initialize global emotion detector
emotion_bridge = EmotionDetectionBridge()

# Sentiment analysis text cleaning is now imported from text_utils.py

# ============================================================================
# SENTIMENT ANALYSIS CLASS
# ============================================================================

class SentimentAnalysisBridge:
    """Sentiment analysis for mental health detection (Anxiety, Stress, Normal)"""

    def __init__(self):
        self.model = None
        self.tfidf_vectorizer = None
        self.label_encoder = None
        self.text_cleaner = None
        self.is_initialized = False
        self.model_accuracy = 0.0
        self.model_f1_score = 0.0
        self.classes = []

    def initialize(self):
        """Initialize sentiment analysis model"""
        try:
            model_path = os.path.join(
                os.path.dirname(__file__),
                'text_model',
                'best_mental_health_model_new.pkl'
            )

            if not os.path.exists(model_path):
                logger.error(f"Model file not found at: {model_path}")
                return False

            model_data = None
            
            # Try joblib first (more robust for sklearn models)
            try:
                import joblib
                model_data = joblib.load(model_path)
                logger.info("Model loaded with joblib")
            except Exception as e:
                logger.warning(f"Joblib load failed: {e}, trying pickle...")
            
            # Fallback to pickle with different approaches
            if model_data is None:
                try:
                    with open(model_path, 'rb') as f:
                        model_data = pickle.load(f)
                    logger.info("Model loaded with pickle")
                except AttributeError as e:
                    # Handle the case where text_cleaner function can't be found
                    logger.warning(f"Pickle AttributeError (likely function reference): {e}")
                    # Try loading with custom unpickler that ignores missing functions
                    import io
                    class CustomUnpickler(pickle.Unpickler):
                        def find_class(self, module, name):
                            # Replace any missing function with our module-level clean_text
                            if name == 'clean_text' or 'clean' in name.lower():
                                return clean_text
                            return super().find_class(module, name)
                    
                    with open(model_path, 'rb') as f:
                        model_data = CustomUnpickler(f).load()
                    logger.info("Model loaded with custom unpickler")

            if model_data is None:
                logger.error("Failed to load model with all methods")
                return False

            # Extract components (support both old and new model key names)
            self.model = model_data['model']
            # New model uses 'tfidf', old model uses 'tfidf_vectorizer'
            self.tfidf_vectorizer = model_data.get('tfidf') or model_data.get('tfidf_vectorizer')
            self.label_encoder = model_data.get('label_encoder')
            # Always use module-level clean_text to avoid pickle issues
            self.text_cleaner = clean_text
            self.model_accuracy = model_data.get('accuracy', 0.0)
            self.model_f1_score = model_data.get('f1_score', 0.0)
            # Get classes from model or label_encoder
            self.classes = model_data.get('classes', [])
            if not self.classes and hasattr(self.model, 'classes_'):
                self.classes = list(self.model.classes_)

            self.is_initialized = True
            logger.info("Sentiment analysis model initialized successfully")
            logger.info(f"Model accuracy: {self.model_accuracy:.4f}, F1-score: {self.model_f1_score:.4f}")
            logger.info(f"Model classes: {self.classes}")

            return True

        except Exception as e:
            logger.error(f"Error initializing sentiment analysis: {e}")
            import traceback
            traceback.print_exc()
            return False

    def predict_sentiment(self, text):
        """
        Predict sentiment and return all three probability scores
        Returns: dict with anxiety_score, stress_score, normal_score (all 0-100%)
        """
        try:
            if not self.is_initialized:
                logger.warning("Sentiment model not initialized, attempting to initialize...")
                if not self.initialize():
                    return {
                        'category': 'normal',
                        'anxiety_score': 0.0,
                        'stress_score': 0.0,
                        'normal_score': 0.0,
                        'error': 'Model not initialized'
                    }

            # Clean the text (use module-level clean_text as fallback)
            cleaned_text = self.text_cleaner(text) if callable(self.text_cleaner) else clean_text(text)

            if not cleaned_text or len(cleaned_text.strip()) == 0:
                return {
                    'category': 'normal',
                    'anxiety_score': 0.0,
                    'stress_score': 0.0,
                    'normal_score': 0.0,
                    'error': 'Empty text after cleaning'
                }

            # Transform using TF-IDF vectorizer
            text_vectorized = self.tfidf_vectorizer.transform([cleaned_text])

            # Make prediction
            prediction = self.model.predict(text_vectorized)[0]
            
            # Handle numeric predictions (new model uses 0,1,2 with label_encoder)
            if self.label_encoder is not None and hasattr(self.label_encoder, 'inverse_transform'):
                try:
                    predicted_category = self.label_encoder.inverse_transform([prediction])[0].lower()
                except:
                    predicted_category = str(prediction).lower()
            else:
                predicted_category = str(prediction).lower()

            # Get probability scores using predict_proba
            probabilities = self.model.predict_proba(text_vectorized)[0]

            # Map probabilities to specific scores
            # Use label_encoder classes if available, otherwise use model classes
            if self.label_encoder is not None and hasattr(self.label_encoder, 'classes_'):
                class_labels = self.label_encoder.classes_
            elif hasattr(self.model, 'classes_'):
                class_labels = self.model.classes_
            else:
                class_labels = ['Anxiety', 'Normal', 'Stress']
            
            prob_dict = {
                str(label).lower(): round(prob * 100, 2)
                for label, prob in zip(class_labels, probabilities)
            }

            anxiety_score = prob_dict.get('anxiety', 0.0)
            stress_score = prob_dict.get('stress', 0.0)
            normal_score = prob_dict.get('normal', 0.0)

            logger.info(f"Sentiment prediction: {predicted_category}")
            logger.info(f"  Anxiety: {anxiety_score}%, Stress: {stress_score}%, Normal: {normal_score}%")

            return {
                'category': predicted_category,
                'anxiety_score': anxiety_score,
                'stress_score': stress_score,
                'normal_score': normal_score,
                'all_probabilities': prob_dict
            }

        except Exception as e:
            logger.error(f"Error predicting sentiment: {e}")
            import traceback
            traceback.print_exc()
            return {
                'category': 'normal',
                'anxiety_score': 0.0,
                'stress_score': 0.0,
                'normal_score': 0.0,
                'error': str(e)
            }

# Initialize global sentiment analyzer
sentiment_analyzer = SentimentAnalysisBridge()

# ============================================================================
# HEART RATE STRESS PREDICTION CLASS
# ============================================================================

class HeartRateStressPrediction:
    """Heart rate stress prediction using RR intervals"""

    def __init__(self):
        self.model = None
        self.scaler = None
        self.feature_names = None
        self.is_initialized = False

    def initialize(self):
        """Initialize heart rate stress prediction model"""
        try:
            # Get absolute path to the model directory
            # Use __file__ to get the directory where app.py is located
            backend_dir = os.path.dirname(os.path.abspath(__file__))
            model_dir = os.path.join(backend_dir, 'heartPredictionModel')

            print(f"\n>> HR Model Initialization:")
            print(f"   Backend dir: {backend_dir}")
            print(f"   Model dir: {model_dir}")
            print(f"   Model dir exists: {os.path.exists(model_dir)}")

            model_path = os.path.join(model_dir, 'stress_model.pkl')
            scaler_path = os.path.join(model_dir, 'stress_scaler.pkl')
            features_path = os.path.join(model_dir, 'feature_names.pkl')

            # Check each file individually
            print(f"   stress_model.pkl: {os.path.exists(model_path)}")
            print(f"   stress_scaler.pkl: {os.path.exists(scaler_path)}")
            print(f"   feature_names.pkl: {os.path.exists(features_path)}")

            if not all([os.path.exists(p) for p in [model_path, scaler_path, features_path]]):
                logger.error(f"Heart rate model files not found in: {model_dir}")
                logger.error(f"Missing files:")
                if not os.path.exists(model_path):
                    logger.error(f"  - {model_path}")
                if not os.path.exists(scaler_path):
                    logger.error(f"  - {scaler_path}")
                if not os.path.exists(features_path):
                    logger.error(f"  - {features_path}")
                return False

            # Helper function to load pkl with joblib fallback
            def load_pkl(path):
                try:
                    import joblib
                    return joblib.load(path)
                except Exception:
                    with open(path, 'rb') as f:
                        return pickle.load(f, encoding='bytes')
            
            # Load model components
            print(f"   Loading stress_model.pkl...")
            self.model = load_pkl(model_path)

            print(f"   Loading stress_scaler.pkl...")
            self.scaler = load_pkl(scaler_path)

            print(f"   Loading feature_names.pkl...")
            self.feature_names = load_pkl(features_path)
            # Convert bytes to string if needed
            if self.feature_names and isinstance(self.feature_names[0], bytes):
                self.feature_names = [f.decode('utf-8') for f in self.feature_names]

            self.is_initialized = True
            print(f"   ✅ Model loaded successfully!")
            print(f"   Model type: {type(self.model)}")
            print(f"   Scaler type: {type(self.scaler)}")
            print(f"   Features: {self.feature_names}")
            
            logger.info("Heart rate stress prediction model initialized successfully")
            logger.info(f"Feature names: {self.feature_names}")

            return True

        except pickle.UnpicklingError as e:
            logger.error(f"Pickle error loading HR stress model: {e}")
            logger.error(f"This usually means the pickle file is corrupted or incompatible")
            logger.error(f"Try regenerating the model files")
            import traceback
            traceback.print_exc()
            return False

        except Exception as e:
            logger.error(f"Error initializing HR stress model: {e}")
            import traceback
            traceback.print_exc()
            return False

    def predict_stress(self, rr_intervals):
        """
        Predict stress from RR intervals
        Args:
            rr_intervals: List of RR interval values in milliseconds
        Returns:
            dict with stress prediction (1=stress, 0=no stress) and score
        """
        try:
            if not self.is_initialized:
                logger.warning("HR stress model not initialized, attempting to initialize...")
                if not self.initialize():
                    return {
                        'stress': 0,
                        'score': 0,
                        'error': 'Model not initialized'
                    }

            if not rr_intervals or len(rr_intervals) == 0:
                return {
                    'stress': 0,
                    'score': 0,
                    'error': 'No RR intervals provided'
                }

            # Calculate HRV features from RR intervals
            features = self._calculate_hrv_features(rr_intervals)

            # Scale features
            features_scaled = self.scaler.transform([features])

            # Predict (1 = stress, 0 = no stress)
            prediction = self.model.predict(features_scaled)[0]

            # Get probability if available
            if hasattr(self.model, 'predict_proba'):
                probabilities = self.model.predict_proba(features_scaled)[0]
                stress_prob = probabilities[1] if len(probabilities) > 1 else probabilities[0]
            else:
                stress_prob = float(prediction)

            logger.info(f"HR Stress Prediction: stress={prediction}, probability={stress_prob:.2%}")

            return {
                'stress': int(prediction),
                'score': 100 if prediction == 1 else 0,
                'probability': float(stress_prob),
                'features': features
            }

        except Exception as e:
            logger.error(f"Error predicting HR stress: {e}")
            import traceback
            traceback.print_exc()
            return {
                'stress': 0,
                'score': 0,
                'error': str(e)
            }

    def _calculate_hrv_features(self, rr_intervals):
        """Calculate HRV features from RR intervals"""
        try:
            rr_array = np.array(rr_intervals, dtype=float)

            # Time-domain features
            mean_rr = np.mean(rr_array)
            std_rr = np.std(rr_array)
            rmssd = np.sqrt(np.mean(np.square(np.diff(rr_array))))

            # Frequency-domain features would go here
            # For now, using basic time-domain features

            # Return features in expected order (matching feature_names)
            features = [mean_rr, std_rr, rmssd]

            logger.info(f"Calculated HRV features: mean={mean_rr:.2f}, std={std_rr:.2f}, rmssd={rmssd:.2f}")

            return features

        except Exception as e:
            logger.error(f"Error calculating HRV features: {e}")
            # Return default features if calculation fails
            return [0.0, 0.0, 0.0]

# Initialize global HR stress predictor
hr_stress_predictor = HeartRateStressPrediction()

# ============================================================================
# MYSQL DATABASE CONFIGURATION
# ============================================================================

# Database configuration imported from config.py (uses environment variables)
# NOTE: Database operations are handled by PHP backend, not Flask
# Flask is only responsible for sentiment analysis
# DB_CONFIG and ENABLE_FLASK_DB imported from config.py

def get_db_connection():
    """Get MySQL database connection"""
    try:
        if not _mysql_available:
            logger.error("MySQL connector not available")
            return None

        connection = mysql.connector.connect(**DB_CONFIG)
        if connection.is_connected():
            return connection
        return None
    except Exception as e:
        logger.error(f"Error connecting to database: {e}")
        return None

def save_journal_to_db(session_code, role, journal_text, anxiety_score=None, depression_score=None, neutral_score=None):
    """
    Save journal entry to MySQL database with all three sentiment scores

    Args:
        session_code: Unique session identifier
        role: 'user' or 'assistant'
        journal_text: The journal text content
        anxiety_score: Anxiety probability score (0-100 percentage)
        depression_score: Depression probability score (0-100 percentage)
        neutral_score: Neutral/Normal probability score (0-100 percentage)

    Returns:
        dict with success status and data
    """
    # Check if database operations are enabled
    if not ENABLE_FLASK_DB:
        logger.info("Database operations disabled in Flask (handled by PHP backend)")
        return {
            'success': True,
            'message': 'Database operations handled by PHP backend',
            'skipped': True
        }

    connection = None
    cursor = None
    try:
        connection = get_db_connection()
        if not connection:
            return {'success': False, 'error': 'Database connection failed'}

        cursor = connection.cursor(dictionary=True)

        # Insert journal entry with all three sentiment scores
        sql = """
            INSERT INTO journal_tbl
            (session_code, role, journal_text, anxiety_score, depression_score, neutral_score, journal_timestamp)
            VALUES (%s, %s, %s, %s, %s, %s, NOW())
        """

        cursor.execute(sql, (session_code, role, journal_text, anxiety_score, depression_score, neutral_score))
        connection.commit()

        session_id = cursor.lastrowid

        logger.info(f"Journal saved to DB: session_code={session_code}, role={role}")
        logger.info(f"  Scores - Anxiety: {anxiety_score}%, Depression: {depression_score}%, Neutral: {neutral_score}%")

        return {
            'success': True,
            'session_id': session_id,
            'session_code': session_code,
            'role': role,
            'anxiety_score': anxiety_score,
            'depression_score': depression_score,
            'neutral_score': neutral_score
        }

    except Exception as e:
        logger.error(f"Error saving journal to database: {e}")
        if connection:
            connection.rollback()
        return {'success': False, 'error': str(e)}

    finally:
        if cursor:
            cursor.close()
        if connection and connection.is_connected():
            connection.close()

@app.route('/health', methods=['GET'])
def health_check():
    """Health check endpoint"""
    return jsonify({'status': 'healthy', 'timestamp': datetime.now().isoformat()})

@app.route('/start_conversation', methods=['POST'])
def start_conversation():
    """Start a new conversation session"""
    try:
        data = request.get_json()
        session_id = data.get('session_id', f"session_{datetime.now().timestamp()}")
        
        # Create new conversation session
        session = ConversationSession(session_id)
        conversation_sessions[session_id] = session
        
        # Generate initial greeting
        initial_prompt = """You are an empathetic AI companion for a journaling app. 
        Start a conversation to help the user express their feelings and share about their day. 
        Begin with a warm, welcoming greeting and ask an open-ended question about how they're feeling right now.
        Keep it concise (2-3 sentences max)."""
        
        response = model.generate_content(initial_prompt)
        ai_message = response.text.strip()

        session.add_message(ai_message, is_user=False)
        session.question_count = 1

        logger.info(f"Started conversation session: {session_id}")

        return jsonify({
            'session_id': session_id,
            'message': ai_message,
            'question_count': session.question_count,
            'conversation_complete': False
        })
        
    except Exception as e:
        logger.error(f"Error starting conversation: {str(e)}")
        return jsonify({'error': 'Failed to start conversation'}), 500

@app.route('/send_message', methods=['POST'])
def send_message():
    """Send a message and get AI response with sentiment analysis"""
    try:
        data = request.get_json()
        session_id = data.get('session_id')
        user_message = data.get('message', '').strip()
        user_emotion = data.get('emotion', '')
        session_code = data.get('session_code', session_id)  # For database saving

        if not session_id or not user_message:
            return jsonify({'error': 'Session ID and message are required'}), 400

        # Get or create session
        if session_id not in conversation_sessions:
            return jsonify({'error': 'Session not found'}), 404

        session = conversation_sessions[session_id]

        # Check if conversation is already complete
        if session.conversation_complete:
            return jsonify({
                'session_id': session_id,
                'message': "Thank you for sharing with me today. I hope our conversation was helpful!",
                'question_count': session.question_count,
                'conversation_complete': True
            })

        # ===== SENTIMENT ANALYSIS FOR USER MESSAGE =====
        sentiment_result = sentiment_analyzer.predict_sentiment(user_message)
        category = sentiment_result.get('category', 'normal')
        anxiety_score = sentiment_result.get('anxiety_score', 0.0)
        depression_score = sentiment_result.get('depression_score', 0.0)
        neutral_score = sentiment_result.get('neutral_score', 0.0)

        logger.info(f"User message sentiment: category={category}")
        logger.info(f"  Anxiety: {anxiety_score}%, Depression: {depression_score}%, Neutral: {neutral_score}%")

        # Save user message to database with all three sentiment scores
        db_result = save_journal_to_db(
            session_code=session_code,
            role='user',
            journal_text=user_message,
            anxiety_score=anxiety_score,
            depression_score=depression_score,
            neutral_score=neutral_score
        )

        if not db_result.get('success'):
            logger.warning(f"Failed to save user message to DB: {db_result.get('error')}")

        # Add user message to session
        session.add_message(user_message, is_user=True, emotion=user_emotion)

        # Generate follow-up question - no artificial limit
        context = session.get_conversation_context()
        context += f"\n\nUser just said: {user_message}"
        if user_emotion:
            context += f"\nDetected emotion: {user_emotion}"
        if category and category != 'normal':
            max_score = max(anxiety_score, depression_score, neutral_score)
            context += f"\nDetected sentiment: {category} (confidence: {max_score}%)"
        context += "\n\nGenerate a thoughtful follow-up question or supportive response to help them continue exploring their feelings or share more about their day. "
        context += "If the user seems satisfied or gives closing cues (like 'that's all', 'nothing else', 'I'm done'), provide a warm closing statement instead of another question."

        response = model.generate_content(context)
        ai_message = response.text.strip()
        session.question_count += 1

        # Add AI response to session
        session.add_message(ai_message, is_user=False)

        # ===== SAVE AI MESSAGE TO DATABASE =====
        # AI messages have all scores set to 0
        ai_db_result = save_journal_to_db(
            session_code=session_code,
            role='assistant',
            journal_text=ai_message,
            anxiety_score=0.0,
            depression_score=0.0,
            neutral_score=0.0
        )

        if not ai_db_result.get('success'):
            logger.warning(f"Failed to save AI message to DB: {ai_db_result.get('error')}")

        logger.info(f"Session {session_id}: Message count: {session.question_count}")

        return jsonify({
            'session_id': session_id,
            'message': ai_message,
            'question_count': session.question_count,
            'conversation_complete': session.conversation_complete,
            'sentiment': {
                'category': category,
                'anxiety_score': anxiety_score,
                'depression_score': depression_score,
                'neutral_score': neutral_score,
                'all_probabilities': sentiment_result.get('all_probabilities', {})
            }
        })

    except Exception as e:
        logger.error(f"Error processing message: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': 'Failed to process message'}), 500

@app.route('/get_conversation', methods=['GET'])
def get_conversation():
    """Get conversation history"""
    try:
        session_id = request.args.get('session_id')
        
        if not session_id or session_id not in conversation_sessions:
            return jsonify({'error': 'Session not found'}), 404
        
        session = conversation_sessions[session_id]
        
        return jsonify({
            'session_id': session_id,
            'messages': session.messages,
            'question_count': session.question_count,
            'conversation_complete': session.conversation_complete,
            'user_emotions': session.user_emotions
        })
        
    except Exception as e:
        logger.error(f"Error getting conversation: {str(e)}")
        return jsonify({'error': 'Failed to get conversation'}), 500

@app.route('/end_conversation', methods=['POST'])
def end_conversation():
    """End a conversation session"""
    try:
        data = request.get_json()
        session_id = data.get('session_id')
        
        if session_id in conversation_sessions:
            session = conversation_sessions[session_id]
            session.conversation_complete = True
            
            return jsonify({
                'session_id': session_id,
                'message': 'Conversation ended successfully',
                'summary': {
                    'total_messages': len(session.messages),
                    'questions_asked': session.question_count,
                    'emotions_detected': session.user_emotions,
                    'duration': str(datetime.now() - session.created_at)
                }
            })
        
        return jsonify({'error': 'Session not found'}), 404
        
    except Exception as e:
        logger.error(f"Error ending conversation: {str(e)}")
        return jsonify({'error': 'Failed to end conversation'}), 500



# ============================================================================
# IMPROVED STT ENDPOINTS (HTTP-based, no WebSocket)
# ============================================================================

@app.route('/stt_start', methods=['POST'])
def stt_start():
    """Start a new STT recording session"""
    try:
        data = request.get_json()
        session_id = data.get('session_id', f"stt_{datetime.now().timestamp()}")
        
        # Create new STT session
        session = STTSession(session_id)
        session.is_recording = True
        stt_sessions[session_id] = session
        
        logger.info(f"Started STT session: {session_id}")
        
        return jsonify({
            'success': True,
            'session_id': session_id,
            'message': 'Recording started'
        })
        
    except Exception as e:
        logger.error(f"STT start error: {str(e)}")
        return jsonify({'error': 'Failed to start STT session'}), 500

@app.route('/stt_send_chunk', methods=['POST'])
def stt_send_chunk():
    """Receive audio chunks during recording"""
    try:
        if not _speech_available:
            return jsonify({'error': 'Speech-to-Text not available'}), 500
        
        session_id = request.form.get('session_id')
        if not session_id or session_id not in stt_sessions:
            return jsonify({'error': 'Invalid session_id'}), 400
        
        session = stt_sessions[session_id]
        
        if 'chunk' not in request.files:
            return jsonify({'error': 'No audio chunk provided'}), 400
        
        # Append chunk to buffer
        chunk_data = request.files['chunk'].read()
        session.audio_buffer.write(chunk_data)
        
        return jsonify({
            'success': True,
            'session_id': session_id,
            'bytes_received': len(chunk_data),
            'total_bytes': session.audio_buffer.tell()
        })
        
    except Exception as e:
        logger.error(f"STT chunk error: {str(e)}")
        return jsonify({'error': 'Failed to process audio chunk'}), 500

@app.route('/stt_stop', methods=['POST'])
def stt_stop():
    """Stop recording and get final transcription"""
    try:
        if not _speech_available:
            return jsonify({'error': 'Speech-to-Text not available'}), 500
        
        data = request.get_json()
        session_id = data.get('session_id')
        language_code = data.get('language_code', SPEECH_LANGUAGE_CODE or 'en-US')
        
        if not session_id or session_id not in stt_sessions:
            return jsonify({'error': 'Invalid session_id'}), 400
        
        session = stt_sessions[session_id]
        session.is_recording = False
        
        # Get all audio data
        audio_data = session.audio_buffer.getvalue()
        
        if not audio_data:
            # Cleanup and return empty
            del stt_sessions[session_id]
            return jsonify({
                'success': True,
                'session_id': session_id,
                'transcript': '',
                'message': 'No audio recorded'
            })
        
        # Transcribe using Google Cloud Speech-to-Text
        credentials = service_account.Credentials.from_service_account_file(
            GCP_SERVICE_ACCOUNT_FILE
        )
        speech_client = speech.SpeechClient(credentials=credentials)
        
        audio = speech.RecognitionAudio(content=audio_data)
        config = speech.RecognitionConfig(
            encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
            sample_rate_hertz=16000,
            language_code=language_code,
            enable_automatic_punctuation=True,
            model='default'
        )
        
        response = speech_client.recognize(config=config, audio=audio)
        
        # Combine all transcripts
        transcripts = []
        confidence_scores = []
        
        for result in response.results:
            if result.alternatives:
                transcripts.append(result.alternatives[0].transcript)
                if result.alternatives[0].confidence:
                    confidence_scores.append(result.alternatives[0].confidence)
        
        final_transcript = ' '.join(transcripts).strip()
        avg_confidence = sum(confidence_scores) / len(confidence_scores) if confidence_scores else 0.0
        
        # Cleanup session
        del stt_sessions[session_id]
        
        logger.info(f"STT session {session_id} completed: {len(final_transcript)} chars")
        
        return jsonify({
            'success': True,
            'session_id': session_id,
            'transcript': final_transcript,
            'confidence': avg_confidence,
            'has_text': bool(final_transcript),
            'duration': str(datetime.now() - session.created_at)
        })
        
    except Exception as e:
        logger.error(f"STT stop error: {str(e)}")
        # Cleanup on error
        if session_id in stt_sessions:
            del stt_sessions[session_id]
        return jsonify({'error': f'Failed to transcribe: {str(e)}'}), 500

@app.route('/stt_cancel', methods=['POST'])
def stt_cancel():
    """Cancel an ongoing STT session"""
    try:
        data = request.get_json()
        session_id = data.get('session_id')
        
        if session_id in stt_sessions:
            del stt_sessions[session_id]
            return jsonify({
                'success': True,
                'message': 'STT session cancelled'
            })
        
        return jsonify({'error': 'Session not found'}), 404
        
    except Exception as e:
        logger.error(f"STT cancel error: {str(e)}")
        return jsonify({'error': 'Failed to cancel session'}), 500

@app.route('/stt', methods=['POST'])
def speech_to_text():
    """Transcribe uploaded audio file using Google Cloud Speech-to-Text.
    Expected form-data:
      - file: audio file (e.g., .wav, .mp3, .raw)
      - language_code (optional): override default language
    """
    try:
        if not _speech_available:
            return jsonify({'error': 'Speech-to-Text dependencies not installed'}), 500

        if 'file' not in request.files:
            return jsonify({'error': 'No file provided'}), 400

        uploaded = request.files['file']
        if uploaded.filename == '':
            return jsonify({'error': 'Empty filename'}), 400

        language_code = request.form.get('language_code', SPEECH_LANGUAGE_CODE or 'en-US')

        # Read file content into memory
        content = uploaded.read()
        if not content:
            return jsonify({'error': 'Empty file content'}), 400

        logger.info(f"Received audio file: {len(content)} bytes")

        # Create Speech client using pre-loaded credentials
        if _gcp_credentials is None:
            return jsonify({'error': 'GCP credentials not configured'}), 500
        speech_client = speech.SpeechClient(credentials=_gcp_credentials)

        # Configure audio for LINEAR16 format (raw PCM)
        audio = speech.RecognitionAudio(content=content)
        config = speech.RecognitionConfig(
            encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,
            sample_rate_hertz=16000,
            language_code=language_code,
            enable_automatic_punctuation=True,
            model='default'
        )

        response = speech_client.recognize(config=config, audio=audio)

        transcripts = []
        for result in response.results:
            if result.alternatives:
                transcripts.append(result.alternatives[0].transcript)

        transcript_text = ' '.join(transcripts).strip()
        
        logger.info(f"Transcription complete: {len(transcript_text)} characters")
        
        return jsonify({
            'transcript': transcript_text,
            'language_code': language_code,
            'has_text': bool(transcript_text)
        })
    except Exception as e:
        logger.error(f"STT error: {str(e)}")
        return jsonify({'error': f'Failed to transcribe audio: {str(e)}'}), 500

# ============================================================================
# EMOTION DETECTION ENDPOINTS
# ============================================================================

@app.route('/emotion_initialize', methods=['POST'])
def emotion_initialize():
    """Initialize emotion detection system"""
    try:
        if not _emotion_detection_available:
            return jsonify({
                'success': False,
                'error': 'Emotion detection dependencies not available',
                'message': 'Install opencv-python and fer packages'
            }), 500

        success = emotion_bridge.initialize()

        return jsonify({
            'success': success,
            'initialized': emotion_bridge.is_initialized,
            'message': 'Emotion detection initialized' if success else 'Failed to initialize'
        })

    except Exception as e:
        logger.error(f"Emotion initialization error: {str(e)}")
        return jsonify({'error': f'Failed to initialize emotion detection: {str(e)}'}), 500

@app.route('/emotion_detect', methods=['POST'])
def emotion_detect():
    """Detect emotion from uploaded image frame"""
    try:
        if not _emotion_detection_available:
            return jsonify({
                'error': 'Emotion detection not available'
            }), 500

        if not emotion_bridge.is_initialized:
            # Try to initialize
            emotion_bridge.initialize()

        if 'frame' not in request.files:
            return jsonify({'error': 'No frame image provided'}), 400

        # Read the uploaded frame
        frame_file = request.files['frame']
        frame_bytes = frame_file.read()

        if not frame_bytes:
            return jsonify({'error': 'Empty frame data'}), 400

        # Detect emotion
        emotion_data = emotion_bridge.detect_emotion_from_frame(frame_bytes)

        logger.info(f"Emotion detected: {emotion_data['dominant_emotion']} ({emotion_data['confidence']:.2f})")

        return jsonify({
            'success': True,
            'emotion': emotion_data['dominant_emotion'],
            'confidence': emotion_data['confidence'],
            'all_emotions': emotion_data['all_emotions'],
            'face_detected': emotion_data['face_detected'],
            'timestamp': emotion_data['timestamp']
        })

    except Exception as e:
        logger.error(f"Emotion detection error: {str(e)}")
        return jsonify({'error': f'Failed to detect emotion: {str(e)}'}), 500

@app.route('/emotion_status', methods=['GET'])
def emotion_status():
    """Get current emotion detection status"""
    try:
        return jsonify({
            'available': _emotion_detection_available,
            'initialized': emotion_bridge.is_initialized,
            'current_emotion': emotion_bridge.current_emotion_data
        })

    except Exception as e:
        logger.error(f"Emotion status error: {str(e)}")
        return jsonify({'error': f'Failed to get emotion status: {str(e)}'}), 500

# ============================================================================
# SENTIMENT ANALYSIS ENDPOINTS
# ============================================================================

@app.route('/sentiment_initialize', methods=['POST'])
def sentiment_initialize():
    """Initialize sentiment analysis model"""
    try:
        success = sentiment_analyzer.initialize()

        return jsonify({
            'success': success,
            'initialized': sentiment_analyzer.is_initialized,
            'accuracy': sentiment_analyzer.model_accuracy,
            'f1_score': sentiment_analyzer.model_f1_score,
            'classes': sentiment_analyzer.classes,
            'message': 'Sentiment analysis initialized' if success else 'Failed to initialize'
        })

    except Exception as e:
        logger.error(f"Sentiment initialization error: {str(e)}")
        return jsonify({'error': f'Failed to initialize sentiment analysis: {str(e)}'}), 500

@app.route('/sentiment_predict', methods=['POST'])
def sentiment_predict():
    """Predict sentiment for given text"""
    try:
        data = request.get_json()
        text = data.get('text', '').strip()

        if not text:
            return jsonify({'error': 'Text is required'}), 400

        # Make prediction
        result = sentiment_analyzer.predict_sentiment(text)

        return jsonify({
            'success': True,
            'text': text,
            'category': result.get('category'),
            'anxiety_score': result.get('anxiety_score'),
            'stress_score': result.get('stress_score'),
            'normal_score': result.get('normal_score'),
            'all_probabilities': result.get('all_probabilities', {}),
            'error': result.get('error')
        })

    except Exception as e:
        logger.error(f"Sentiment prediction error: {str(e)}")
        return jsonify({'error': f'Failed to predict sentiment: {str(e)}'}), 500

@app.route('/sentiment_status', methods=['GET'])
def sentiment_status():
    """Get sentiment analysis status"""
    try:
        return jsonify({
            'initialized': sentiment_analyzer.is_initialized,
            'accuracy': sentiment_analyzer.model_accuracy,
            'f1_score': sentiment_analyzer.model_f1_score,
            'classes': sentiment_analyzer.classes
        })

    except Exception as e:
        logger.error(f"Sentiment status error: {str(e)}")
        return jsonify({'error': f'Failed to get sentiment status: {str(e)}'}), 500

# ============================================================================
# UTILITY FUSION CALCULATION ENDPOINT
# ============================================================================

@app.route('/calculate_utility_scores', methods=['POST'])
def calculate_utility_scores():
    """
    Calculate utility fusion scores from heartbeat, emotion, and journal data
    Expects JSON with: user_id, session_code
    Returns: anxiety, stress, and normal scores (normalized to 100%)
    """
    try:
        data = request.get_json()
        user_id = data.get('user_id')
        session_code = data.get('session_code')

        # Heartbeat data from request (retrieved from PHP by Flutter)
        heartbeat_data = data.get('heartbeat_data', [])
        emotion_data = data.get('emotion_data', [])
        journal_data = data.get('journal_data', [])

        if not user_id or not session_code:
            return jsonify({'error': 'user_id and session_code are required'}), 400

        logger.info(f"Calculating utility scores for user={user_id}, session={session_code}")
        logger.info(f"Received {len(heartbeat_data)} heartbeat records, {len(emotion_data)} emotion records, {len(journal_data)} journal records")

        # ===== 1. PROCESS HEARTBEAT DATA =====
        hr_stress_score = 0
        valid_rr_intervals = []

        for hb in heartbeat_data:
            quality = float(hb.get('quality_score', 0))
            rr_interval = float(hb.get('rr_interval', 0))

            # Filter: quality >= 50
            if quality >= 50 and rr_interval > 0:
                valid_rr_intervals.append(rr_interval)

        logger.info(f"Valid RR intervals (quality >= 50): {len(valid_rr_intervals)}")

        # Predict stress using HR model
        if len(valid_rr_intervals) > 0:
            hr_prediction = hr_stress_predictor.predict_stress(valid_rr_intervals)
            hr_stress_score = hr_prediction.get('score', 0)  # 100 if stress, 0 if not
            logger.info(f"HR Stress Prediction: {hr_stress_score} (stress={hr_prediction.get('stress')})")
        else:
            logger.warning("No valid RR intervals, using HR stress score = 0")

        # ===== 2. PROCESS EMOTION DATA =====
        fear_scores = []
        angry_scores = []
        sad_scores = []
        neutral_scores = []

        for emotion in emotion_data:
            face_exist = emotion.get('face_exist', 'no')

            # Filter: face_exist = 'yes'
            if face_exist.lower() == 'yes':
                fear_scores.append(float(emotion.get('fear_score', 0)))
                angry_scores.append(float(emotion.get('angry_score', 0)))
                sad_scores.append(float(emotion.get('sad_score', 0)))
                neutral_scores.append(float(emotion.get('neutral_score', 0)))

        # Calculate averages
        avg_fear = np.mean(fear_scores) if fear_scores else 0.0
        avg_angry = np.mean(angry_scores) if angry_scores else 0.0
        avg_sad = np.mean(sad_scores) if sad_scores else 0.0
        avg_neutral = np.mean(neutral_scores) if neutral_scores else 0.0

        logger.info(f"Emotion averages: fear={avg_fear:.2f}%, angry={avg_angry:.2f}%, sad={avg_sad:.2f}%, neutral={avg_neutral:.2f}%")

        # ===== 3. PROCESS JOURNAL DATA (USER MESSAGES ONLY) =====
        anxiety_scores = []
        stress_scores = []
        normal_scores = []

        for journal in journal_data:
            # Only count USER messages, not Gemini/AI responses
            role = journal.get('role', '').lower()
            if role == 'user':
                anxiety_scores.append(float(journal.get('anxiety_score', 0)))
                stress_scores.append(float(journal.get('stress_score', 0)))
                normal_scores.append(float(journal.get('normal_score', 0)))

        # Calculate averages (divided by number of USER messages only)
        text_anxiety = np.mean(anxiety_scores) if anxiety_scores else 0.0
        text_stress = np.mean(stress_scores) if stress_scores else 0.0
        text_normal = np.mean(normal_scores) if normal_scores else 0.0

        logger.info(f"Journal averages (user messages only): anxiety={text_anxiety:.2f}, stress={text_stress:.2f}, normal={text_normal:.2f}")
        logger.info(f"User message count: {len(anxiety_scores)}")

        # ===== 4. UTILITY FUSION CALCULATION =====
        # Updated weightage: Text Sentiment = 60%, Emotion = 25%, HR = 15%

        # Anxiety score calculation
        anxiety_raw = (
            0.60 * text_anxiety +
            0.25 * (0.45 * avg_fear + 0.25 * avg_sad + 0.20 * avg_angry) +
            0.15 * hr_stress_score
        )

        # Stress score calculation
        stress_raw = (
            0.60 * text_stress +
            0.25 * (0.35 * avg_angry + 0.30 * avg_fear + 0.20 * avg_sad) +
            0.15 * hr_stress_score
        )

        # Normal score calculation - USE NEUTRAL EMOTION DIRECTLY
        normal_raw = (
            0.60 * text_normal +
            0.25 * avg_neutral +  # Use neutral emotion score directly
            0.15 * (100 - hr_stress_score)  # Inverse of HR stress
        )

        logger.info(f"Raw scores: anxiety={anxiety_raw:.2f}, stress={stress_raw:.2f}, normal={normal_raw:.2f}")

        # ===== 5. SOFTMAX NORMALIZATION =====
        scores = np.array([anxiety_raw, stress_raw, normal_raw])
        exp_scores = np.exp(scores / 10)
        normalized = (exp_scores / np.sum(exp_scores)) * 100

        final_anxiety = float(normalized[0])
        final_stress = float(normalized[1])
        final_normal = float(normalized[2])

        logger.info(f"Normalized scores: anxiety={final_anxiety:.2f}%, stress={final_stress:.2f}%, normal={final_normal:.2f}%")
        logger.info(f"Sum check: {final_anxiety + final_stress + final_normal:.2f}% (should be 100%)")

        return jsonify({
            'success': True,
            'user_id': user_id,
            'session_code': session_code,
            'anxiety_score': round(final_anxiety, 2),
            'stress_score': round(final_stress, 2),
            'normal_score': round(final_normal, 2),
            'raw_scores': {
                'anxiety': round(anxiety_raw, 2),
                'stress': round(stress_raw, 2),
                'normal': round(normal_raw, 2)
            },
            'input_stats': {
                'hr_stress': hr_stress_score,
                'valid_rr_intervals': len(valid_rr_intervals),
                'emotion_records': len(fear_scores),
                'journal_records': len(anxiety_scores),
                'avg_fear': round(avg_fear, 2),
                'avg_angry': round(avg_angry, 2),
                'avg_sad': round(avg_sad, 2),
                'avg_neutral': round(avg_neutral, 2),
                'text_anxiety': round(text_anxiety, 2),
                'text_stress': round(text_stress, 2),
                'text_normal': round(text_normal, 2)
            }
        })

    except Exception as e:
        logger.error(f"Error calculating utility scores: {str(e)}")
        import traceback
        traceback.print_exc()
        return jsonify({'error': f'Failed to calculate utility scores: {str(e)}'}), 500

# ============================================================================
# MODEL INITIALIZATION ON STARTUP (for both direct run and gunicorn)
# ============================================================================

def initialize_models():
    """Initialize all ML models on startup"""
    print("\n>> Initializing ML models...")
    
    # Initialize emotion detection (haarcascade + FER)
    print(">> Initializing emotion detection...")
    if _emotion_detection_available:
        if emotion_bridge.initialize():
            print(">> Emotion detection ready!")
            print(f"   Haarcascade: loaded")
        else:
            print(">> WARNING: Emotion detection initialization failed")
    else:
        print(">> WARNING: Emotion detection not available (missing dependencies)")
    
    # Initialize sentiment analysis model
    print("\n>> Initializing sentiment analysis model...")
    if sentiment_analyzer.initialize():
        print(f">> Sentiment analysis ready! (Accuracy: {sentiment_analyzer.model_accuracy:.2%})")
        print(f"   Classes: {', '.join(str(c) for c in sentiment_analyzer.classes)}")
    else:
        print(">> WARNING: Sentiment analysis initialization failed")
    
    # Initialize HR stress prediction model
    print("\n>> Initializing HR stress prediction model...")
    if hr_stress_predictor.initialize():
        print(f">> HR stress prediction ready!")
        print(f"   Features: {', '.join(hr_stress_predictor.feature_names) if hr_stress_predictor.feature_names else 'Unknown'}")
    else:
        print(">> WARNING: HR stress prediction initialization failed")
    
    print("\n>> Model initialization complete!")

# Initialize models when module is loaded (works with gunicorn)
initialize_models()

# ============================================================================
# STATIC FILE SERVING (For Flutter App to download models)
# ============================================================================

@app.route('/models/<path:filename>')
def serve_models(filename):
    """Serve model files (XML, PKL) to the Flutter app"""
    # Only allow specific file types for security
    allowed_extensions = {'.xml', '.pkl', '.json', '.txt'}
    file_ext = os.path.splitext(filename)[1].lower()
    
    if file_ext not in allowed_extensions:
        return jsonify({'error': 'File type not allowed'}), 403
        
    return send_from_directory(os.path.dirname(os.path.abspath(__file__)), filename)

@app.route('/haarcascade_frontalface_default.xml')
def serve_cascade():
    """Direct shortcut to serve the haarcascade file"""
    return send_from_directory(os.path.dirname(os.path.abspath(__file__)), 'haarcascade_frontalface_default.xml')

if __name__ == '__main__':
    print(">> Starting Gemini AI Journaling Backend...")
    print(f">> API Key configured: {'YES' if GEMINI_API_KEY else 'NO'}")
    print(f">> Server will be available at: http://{SERVER_IP}:{SERVER_PORT}")
    print(f">> Also accessible via: http://localhost:{SERVER_PORT}")
    print("\n>> Available endpoints:")
    print("\n  Conversation:")
    print("    - POST /start_conversation - Start new conversation")
    print("    - POST /send_message - Send message and get response (with sentiment analysis)")
    print("    - GET /get_conversation - Get conversation history")
    print("    - POST /end_conversation - End conversation")

    print("\n  Speech-to-Text:")
    print("    - POST /stt_start - Start STT recording session")
    print("    - POST /stt_send_chunk - Send audio chunk (optional)")
    print("    - POST /stt_stop - Stop recording and get transcript")
    print("    - POST /stt_cancel - Cancel recording session")
    print("    - POST /stt - Simple file upload STT")
    print("\n  Emotion Detection:")
    print("    - POST /emotion_initialize - Initialize emotion detection")
    print("    - POST /emotion_detect - Detect emotion from image frame")
    print("    - GET /emotion_status - Get emotion detection status")
    print("\n  Sentiment Analysis:")
    print("    - POST /sentiment_initialize - Initialize sentiment analysis model")
    print("    - POST /sentiment_predict - Predict sentiment for text")
    print("    - GET /sentiment_status - Get sentiment analysis status")
    print("\n  Utility Fusion:")
    print("    - POST /calculate_utility_scores - Calculate fused mental health scores")
    print("\n  System:")
    print("    - GET /health - Health check")

    print("\n" + "="*60)
    print("Server starting...")
    print("="*60 + "\n")

    # Run without debug mode to prevent constant restarts
    app.run(debug=False, host='0.0.0.0', port=SERVER_PORT)