File size: 76,026 Bytes
1949eee
d61ddbe
 
 
69418bc
d61ddbe
 
 
 
 
 
 
1949eee
d61ddbe
 
 
69418bc
d61ddbe
1eb3ba2
69418bc
 
 
1eb3ba2
69418bc
 
d61ddbe
69418bc
d61ddbe
 
69418bc
 
d61ddbe
 
 
69418bc
1949eee
69418bc
1949eee
d61ddbe
69418bc
 
1949eee
 
1eb3ba2
69418bc
 
 
 
 
 
 
d61ddbe
69418bc
 
 
 
1949eee
 
 
 
 
 
 
 
 
d61ddbe
1eb3ba2
 
d61ddbe
1eb3ba2
 
 
d61ddbe
1949eee
69418bc
1949eee
 
 
 
69418bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d61ddbe
69418bc
d61ddbe
69418bc
 
 
 
 
 
 
 
 
 
1949eee
69418bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d61ddbe
69418bc
d61ddbe
69418bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eb3ba2
69418bc
1eb3ba2
69418bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eb3ba2
69418bc
1eb3ba2
69418bc
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eb3ba2
1949eee
 
 
 
 
d61ddbe
 
 
1949eee
 
69418bc
1949eee
69418bc
1949eee
 
 
69418bc
1949eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69418bc
d61ddbe
1949eee
d61ddbe
 
 
1949eee
 
 
d61ddbe
 
 
1949eee
 
 
 
 
d61ddbe
 
 
 
1949eee
 
d61ddbe
 
 
 
 
1949eee
d61ddbe
 
 
 
 
1eb3ba2
 
 
69418bc
1949eee
d61ddbe
 
1949eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d61ddbe
 
 
 
1949eee
 
d61ddbe
1949eee
d61ddbe
1949eee
 
 
 
d61ddbe
 
 
 
1949eee
 
 
 
69418bc
d61ddbe
 
1949eee
d61ddbe
1949eee
 
d61ddbe
1949eee
 
d61ddbe
 
 
1949eee
d61ddbe
1949eee
 
 
 
69418bc
d61ddbe
1949eee
 
d61ddbe
1949eee
 
d61ddbe
1949eee
 
d61ddbe
 
 
 
1949eee
 
 
 
 
 
 
 
d61ddbe
1949eee
 
 
d61ddbe
1949eee
 
d61ddbe
1949eee
 
69418bc
1eb3ba2
69418bc
 
1eb3ba2
 
69418bc
1949eee
69418bc
 
 
 
 
 
 
 
 
 
1eb3ba2
 
1949eee
69418bc
1949eee
69418bc
 
 
 
 
 
 
1eb3ba2
69418bc
1eb3ba2
1949eee
 
 
 
 
 
1eb3ba2
1949eee
 
1eb3ba2
69418bc
 
1eb3ba2
1949eee
 
 
69418bc
1949eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eb3ba2
1949eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1eb3ba2
69418bc
1949eee
 
 
69418bc
 
 
 
 
 
1949eee
69418bc
1949eee
 
 
 
 
69418bc
1949eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69418bc
1949eee
 
 
 
69418bc
 
 
1949eee
69418bc
1949eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69418bc
 
1949eee
69418bc
1949eee
 
 
69418bc
 
1949eee
69418bc
1949eee
 
 
69418bc
 
1949eee
69418bc
1949eee
 
69418bc
 
 
1949eee
69418bc
1949eee
 
 
69418bc
1949eee
69418bc
 
 
 
1949eee
69418bc
 
 
 
d61ddbe
 
1949eee
 
 
69418bc
1949eee
 
69418bc
1949eee
 
69418bc
1949eee
 
 
 
 
 
d61ddbe
69418bc
 
 
 
 
1949eee
 
 
 
 
 
 
 
 
69418bc
 
 
 
 
1eb3ba2
69418bc
1949eee
 
69418bc
1949eee
69418bc
 
 
1949eee
 
 
 
 
 
 
 
 
 
 
 
69418bc
1949eee
 
69418bc
 
1949eee
69418bc
 
 
 
 
 
 
 
 
 
1949eee
 
 
69418bc
 
 
1949eee
 
 
 
 
 
 
 
 
 
 
69418bc
1949eee
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69418bc
 
 
 
1949eee
1eb3ba2
69418bc
 
 
1949eee
 
 
 
 
 
 
 
 
69418bc
1949eee
69418bc
1949eee
 
 
 
69418bc
 
1949eee
69418bc
1949eee
 
69418bc
1949eee
1eb3ba2
1949eee
 
 
 
 
 
69418bc
1949eee
 
69418bc
 
1949eee
 
 
 
 
69418bc
1949eee
 
 
 
 
d61ddbe
69418bc
1949eee
69418bc
 
 
 
1949eee
69418bc
1949eee
1eb3ba2
 
 
1949eee
69418bc
1949eee
 
69418bc
1949eee
1eb3ba2
 
1949eee
1eb3ba2
 
 
69418bc
1949eee
 
 
 
 
1eb3ba2
1949eee
 
1eb3ba2
1949eee
 
 
 
 
 
 
 
 
 
69418bc
 
1eb3ba2
69418bc
1949eee
 
 
 
 
 
 
1eb3ba2
69418bc
1949eee
d61ddbe
 
 
 
 
1949eee
 
 
69418bc
 
1949eee
 
69418bc
 
d61ddbe
 
 
69418bc
d61ddbe
 
 
1949eee
 
 
 
d61ddbe
1949eee
 
 
 
69418bc
d61ddbe
69418bc
 
 
d61ddbe
 
 
 
 
 
 
69418bc
1949eee
 
d61ddbe
69418bc
d61ddbe
1949eee
 
 
 
 
 
d61ddbe
 
1eb3ba2
1949eee
69418bc
1eb3ba2
69418bc
 
 
1949eee
1eb3ba2
1949eee
69418bc
 
 
1eb3ba2
1949eee
1eb3ba2
 
1949eee
1eb3ba2
1949eee
 
69418bc
1eb3ba2
 
69418bc
1949eee
1eb3ba2
69418bc
1949eee
1eb3ba2
69418bc
d61ddbe
69418bc
d61ddbe
69418bc
1949eee
69418bc
1949eee
d61ddbe
1949eee
 
69418bc
1949eee
 
 
 
 
 
69418bc
1949eee
 
69418bc
 
 
1949eee
 
 
 
 
 
69418bc
1949eee
 
 
 
69418bc
1949eee
 
69418bc
1949eee
 
69418bc
1949eee
 
69418bc
1949eee
69418bc
 
1949eee
 
69418bc
 
1949eee
69418bc
 
 
 
1949eee
 
69418bc
 
 
1949eee
 
 
69418bc
 
1949eee
 
 
69418bc
 
1949eee
 
69418bc
1949eee
 
69418bc
 
1949eee
 
69418bc
 
 
1949eee
69418bc
1949eee
 
 
69418bc
1949eee
 
 
 
 
 
 
 
 
 
 
 
69418bc
 
 
1949eee
69418bc
1949eee
 
 
69418bc
1949eee
 
 
 
 
 
 
 
 
69418bc
1949eee
69418bc
 
 
1949eee
 
 
69418bc
1949eee
 
 
 
69418bc
1949eee
69418bc
d61ddbe
 
 
1949eee
69418bc
 
1949eee
 
d61ddbe
 
1949eee
 
 
69418bc
 
1949eee
69418bc
 
1eb3ba2
1949eee
 
69418bc
1949eee
69418bc
1949eee
 
 
 
69418bc
 
 
 
d61ddbe
69418bc
 
d61ddbe
69418bc
 
 
 
 
 
 
1949eee
69418bc
1949eee
69418bc
1949eee
69418bc
1949eee
d61ddbe
 
69418bc
 
1eb3ba2
69418bc
1949eee
69418bc
1949eee
 
69418bc
1949eee
1eb3ba2
1949eee
 
69418bc
 
1949eee
69418bc
 
 
 
 
 
 
1949eee
 
69418bc
 
 
 
1949eee
 
 
69418bc
 
 
 
1949eee
 
69418bc
1949eee
69418bc
 
1949eee
69418bc
 
1949eee
69418bc
1949eee
69418bc
 
 
 
 
1949eee
 
 
 
69418bc
 
 
 
 
 
 
d61ddbe
69418bc
1949eee
 
69418bc
 
1949eee
 
 
69418bc
 
d61ddbe
1949eee
 
69418bc
1949eee
 
 
 
 
 
 
 
 
 
 
69418bc
 
 
 
d61ddbe
1949eee
 
 
 
 
 
69418bc
 
 
 
 
1949eee
69418bc
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
# filename: app_openai_no_serper.py
import gradio as gr
import pandas as pd
import numpy as np
# import matplotlib.pyplot as plt # Not directly used for plotting
import plotly.graph_objects as go
import plotly.express as px
from datetime import datetime, timedelta
import random
import json
import os
import time
import requests # Keep for potential future internal API calls if needed, but not for Serper
from typing import List, Dict, Any, Optional
import logging
from dotenv import load_dotenv
# import pytz # Not used
import uuid
import re
# import base64 # Not used
# from io import BytesIO # Not used
# from PIL import Image # Not used

# --- Use OpenAI library ---
import openai

# --- Load environment variables ---
load_dotenv()

# --- Set up logging ---
logging.basicConfig(level=logging.INFO,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# --- Configure API keys ---
# Make sure you have OPENAI_API_KEY in your .env file or environment
OPENAI_API_KEY = os.getenv("OPENAI_API_KEY")
# SERPER_API_KEY = os.getenv("SERPER_API_KEY") # Removed Serper key

if not OPENAI_API_KEY:
    logger.warning("OPENAI_API_KEY not found. AI features will not work.")
# if not SERPER_API_KEY: # Removed Serper check
#     logger.warning("SERPER_API_KEY not found. Web search features will not work.")

# --- Initialize the OpenAI client ---
try:
    client = openai.OpenAI(api_key=OPENAI_API_KEY)
    logger.info("OpenAI client initialized successfully.")
except Exception as e:
    logger.error(f"Failed to initialize OpenAI client: {e}")
    client = None

# --- Model configuration ---
MODEL_ID = "gpt-4o" # Use OpenAI GPT-4o model

# --- Constants ---
EMOTIONS = ["Unmotivated 😩", "Anxious πŸ˜₯", "Confused πŸ€”", "Excited πŸŽ‰", "Overwhelmed 🀯", "Discouraged πŸ˜”"]
# Added Emojis and changed label text
GOAL_TYPES = [
    "Get a job at a big company 🏒",
    "Find an internship πŸŽ“",
    "Change careers πŸš€",
    "Improve skills πŸ’‘",
    "Network better 🀝"
]
USER_DB_PATH = "user_database.json"
RESUME_FOLDER = "user_resumes"
PORTFOLIO_FOLDER = "user_portfolios"

# Ensure folders exist
os.makedirs(RESUME_FOLDER, exist_ok=True)
os.makedirs(PORTFOLIO_FOLDER, exist_ok=True)

# --- Tool Definitions for OpenAI (Removed Job Search Tool) ---
tools_list = [
    # { # Removed get_job_opportunities tool definition
    #     "type": "function",
    #     "function": { ... }
    # },
    {
        "type": "function",
        "function": {
            "name": "generate_document_template",
            "description": "Generate a document template (like a resume or cover letter) based on type, career field, and experience level.",
            "parameters": {
                "type": "object",
                "properties": {
                    "document_type": {
                        "type": "string",
                        "description": "Type of document (e.g., Resume, Cover Letter, Self-introduction).",
                    },
                    "career_field": {
                        "type": "string",
                        "description": "The career field or industry.",
                    },
                    "experience_level": {
                        "type": "string",
                        "description": "User's experience level (e.g., Entry, Mid, Senior).",
                    },
                },
                "required": ["document_type"],
            },
        }
    },
    {
        "type": "function",
        "function": {
            "name": "create_personalized_routine",
            "description": "Create a personalized daily or weekly career development routine based on the user's current emotion, goals, and available time.",
            "parameters": {
                "type": "object",
                "properties": {
                    "emotion": {
                        "type": "string",
                        "description": "User's current primary emotional state (e.g., Unmotivated, Anxious). Needs to be one of the predefined emotions.",
                    },
                    "goal": {
                        "type": "string",
                        "description": "User's specific career goal for this routine.",
                    },
                    "available_time_minutes": {
                        "type": "integer",
                        "description": "Available time in minutes per day (default 60).",
                    },
                    "routine_length_days": {
                        "type": "integer",
                        "description": "Length of the routine in days (default 7).",
                    },
                },
                "required": ["emotion", "goal"],
            },
        }
    },
    {
        "type": "function",
        "function": {
            "name": "analyze_resume",
            "description": "Analyze the provided resume text and provide feedback, comparing it against the user's stated career goal.",
            "parameters": {
                "type": "object",
                "properties": {
                    "resume_text": {
                        "type": "string",
                        "description": "The full text of the user's resume.",
                    },
                    "career_goal": {
                        "type": "string",
                        "description": "The user's career goal or target job/industry to analyze against.",
                    },
                },
                "required": ["resume_text", "career_goal"],
            },
        }
    },
    {
        "type": "function",
        "function": {
            "name": "analyze_portfolio",
            "description": "Analyze a user's portfolio based on a URL (if provided) and a description, offering feedback relative to their career goal.",
            "parameters": {
                "type": "object",
                "properties": {
                    "portfolio_url": {
                        "type": "string",
                        "description": "URL to the user's online portfolio (optional).",
                    },
                    "portfolio_description": {
                        "type": "string",
                        "description": "Detailed description of the portfolio's content, purpose, and structure.",
                    },
                    "career_goal": {
                        "type": "string",
                        "description": "The user's career goal or target job/industry to analyze against.",
                    },
                },
                "required": ["portfolio_description", "career_goal"],
            },
        }
    },
     {
        "type": "function",
        "function": {
            "name": "extract_and_rate_skills_from_resume",
            "description": "Extracts key skills from resume text and rates them on a scale of 1-10 based on apparent proficiency shown in the resume.",
            "parameters": {
                "type": "object",
                "properties": {
                    "resume_text": {
                        "type": "string",
                        "description": "The full text of the user's resume.",
                    },
                     "max_skills": {
                        "type": "integer",
                        "description": "Maximum number of skills to extract (default 8).",
                    },
                },
                "required": ["resume_text"],
            },
        }
    }
]

# --- User Database Functions ---
# (Keep load_user_database, save_user_database, get_user_profile,
#  update_user_profile, add_task_to_user, add_emotion_record,
#  add_routine_to_user, save_user_resume, save_user_portfolio,
#  add_recommendation_to_user, add_chat_message - unchanged from previous corrected version)
def load_user_database():
    """Load user database from JSON file or create if it doesn't exist"""
    try:
        # Ensure correct encoding for wider compatibility
        with open(USER_DB_PATH, 'r', encoding='utf-8') as file:
            db = json.load(file)
            # Validate and fix chat history structure
            for user_id in db.get('users', {}):
                profile = db['users'][user_id]
                if 'chat_history' not in profile or not isinstance(profile['chat_history'], list):
                    profile['chat_history'] = []
                else:
                    fixed_history = []
                    for msg in profile['chat_history']:
                        if isinstance(msg, dict) and 'role' in msg and 'content' in msg:
                             # Ensure content is string for user/assistant if not None
                             if msg['role'] in ['user', 'assistant'] and msg['content'] is not None and not isinstance(msg['content'], str):
                                 msg['content'] = str(msg['content'])
                             fixed_history.append(msg)
                        elif isinstance(msg, dict) and msg.get('role') == 'tool' and all(k in msg for k in ['tool_call_id', 'name', 'content']):
                             # Ensure tool content is string
                             if not isinstance(msg['content'], str):
                                 msg['content'] = json.dumps(msg['content']) if msg['content'] is not None else ""
                             fixed_history.append(msg)
                        else:
                            # Attempt to fix older formats or log invalid message
                            if isinstance(msg, dict) and 'message' in msg and 'role' in msg:
                                msg['content'] = str(msg.pop('message'))
                                fixed_history.append(msg)
                            else:
                                logger.warning(f"Skipping invalid chat message structure for user {user_id}: {msg}")
                    profile['chat_history'] = fixed_history

                # Ensure recommendations is a list
                if 'recommendations' not in profile or not isinstance(profile['recommendations'], list):
                    profile['recommendations'] = []

            return db
    except (FileNotFoundError, json.JSONDecodeError):
        logger.info(f"Database file '{USER_DB_PATH}' not found or invalid. Creating new one.")
        db = {'users': {}}
        save_user_database(db)
        return db
    except Exception as e:
         logger.error(f"Error loading user database from {USER_DB_PATH}: {e}")
         return {'users': {}} # Return empty DB on critical error

def save_user_database(db):
    """Save user database to JSON file"""
    try:
        with open(USER_DB_PATH, 'w', encoding='utf-8') as file:
            json.dump(db, file, indent=4, ensure_ascii=False)
    except Exception as e:
        logger.error(f"Error saving user database to {USER_DB_PATH}: {e}")

def get_user_profile(user_id):
    """Get user profile from database or create new one"""
    db = load_user_database()
    if user_id not in db.get('users', {}):
        db['users'] = db.get('users', {}) # Ensure 'users' key exists
        db['users'][user_id] = {
            "user_id": user_id,
            "name": "",
            "location": "",
            "current_emotion": "",
            "career_goal": "", # Renamed from career_goal in UI, but keep key consistent internally for now
            "progress_points": 0,
            "completed_tasks": [],
            "upcoming_events": [],
            "routine_history": [],
            "daily_emotions": [],
            "resume_path": "",
            "portfolio_path": "",
            "recommendations": [],
            "chat_history": [], # Initialize chat history
            "joined_date": datetime.now().isoformat()
        }
        save_user_database(db)
    # Validate essential lists exist
    profile = db.get('users', {}).get(user_id, {})
    if 'chat_history' not in profile or not isinstance(profile.get('chat_history'), list):
         profile['chat_history'] = []
         # save_user_database(db) # Avoid saving just for this check unless needed
    if 'recommendations' not in profile or not isinstance(profile.get('recommendations'), list):
         profile['recommendations'] = []
    if 'daily_emotions' not in profile or not isinstance(profile.get('daily_emotions'), list):
         profile['daily_emotions'] = []
    if 'completed_tasks' not in profile or not isinstance(profile.get('completed_tasks'), list):
         profile['completed_tasks'] = []
    if 'routine_history' not in profile or not isinstance(profile.get('routine_history'), list):
         profile['routine_history'] = []


    return profile

def update_user_profile(user_id, updates):
    """Update user profile with new information"""
    db = load_user_database()
    if user_id in db.get('users', {}):
        profile = db['users'][user_id]
        for key, value in updates.items():
            profile[key] = value
        save_user_database(db)
        return profile
    else:
         logger.warning(f"Attempted to update non-existent user profile: {user_id}")
         return None

def add_task_to_user(user_id, task):
    """Add a new task to user's completed tasks"""
    db = load_user_database()
    profile = db.get('users', {}).get(user_id)
    if profile:
        if 'completed_tasks' not in profile or not isinstance(profile['completed_tasks'], list):
            profile['completed_tasks'] = []

        task_with_date = {
            "task": task,
            "date": datetime.now().isoformat() # Use ISO format
        }
        profile['completed_tasks'].append(task_with_date)
        profile['progress_points'] = profile.get('progress_points', 0) + random.randint(10, 25)
        save_user_database(db)
        return profile
    return None

def add_emotion_record(user_id, emotion):
    """Add a new emotion record to user's daily emotions"""
    cleaned_emotion = emotion.split(" ")[0] if " " in emotion else emotion
    db = load_user_database()
    profile = db.get('users', {}).get(user_id)
    if profile:
        if 'daily_emotions' not in profile or not isinstance(profile['daily_emotions'], list):
            profile['daily_emotions'] = []

        emotion_record = {
            "emotion": cleaned_emotion, # Store cleaned emotion
            "date": datetime.now().isoformat() # Use ISO format
        }
        profile['daily_emotions'].append(emotion_record)
        profile['current_emotion'] = cleaned_emotion
        save_user_database(db)
        return profile
    return None

def add_routine_to_user(user_id, routine):
    """Add a new routine to user's routine history"""
    db = load_user_database()
    profile = db.get('users', {}).get(user_id)
    if profile:
        if 'routine_history' not in profile or not isinstance(profile['routine_history'], list):
            profile['routine_history'] = []
        try:
            days_delta = int(routine.get('days', 7))
        except (ValueError, TypeError): days_delta = 7
        end_date = (datetime.now() + timedelta(days=days_delta)).isoformat()
        routine_with_date = {
            "routine": routine,
            "start_date": datetime.now().isoformat(),
            "end_date": end_date, "completion": 0
        }
        profile['routine_history'].insert(0, routine_with_date)
        profile['routine_history'] = profile['routine_history'][:10]
        save_user_database(db)
        return profile
    return None

def save_user_resume(user_id, resume_text):
    """Save user's resume text to file and update profile path."""
    if not resume_text: return None
    filename = f"{user_id}_resume.txt"
    filepath = os.path.join(RESUME_FOLDER, filename)
    try:
        with open(filepath, 'w', encoding='utf-8') as file: file.write(resume_text)
        update_user_profile(user_id, {"resume_path": filepath})
        logger.info(f"Resume saved for user {user_id} at {filepath}")
        return filepath
    except Exception as e:
        logger.error(f"Error saving resume for user {user_id}: {e}")
        return None

def save_user_portfolio(user_id, portfolio_url, portfolio_description):
    """Save user's portfolio info (URL and description) to file."""
    if not portfolio_description: return None
    filename = f"{user_id}_portfolio.json"
    filepath = os.path.join(PORTFOLIO_FOLDER, filename)
    portfolio_content = {"url": portfolio_url, "description": portfolio_description, "saved_date": datetime.now().isoformat()}
    try:
        with open(filepath, 'w', encoding='utf-8') as file: json.dump(portfolio_content, file, indent=4, ensure_ascii=False)
        update_user_profile(user_id, {"portfolio_path": filepath})
        logger.info(f"Portfolio info saved for user {user_id} at {filepath}")
        return filepath
    except Exception as e:
        logger.error(f"Error saving portfolio info for user {user_id}: {e}")
        return None

def add_recommendation_to_user(user_id, recommendation):
    """Add a new recommendation object to user's list"""
    db = load_user_database()
    profile = db.get('users', {}).get(user_id)
    if profile:
        if 'recommendations' not in profile or not isinstance(profile['recommendations'], list): profile['recommendations'] = []
        recommendation_with_date = {"recommendation": recommendation, "date": datetime.now().isoformat(), "status": "pending"}
        profile['recommendations'].insert(0, recommendation_with_date)
        profile['recommendations'] = profile['recommendations'][:20]
        save_user_database(db)
        return profile
    return None

def add_chat_message(user_id, role, content):
    """Add a message to the user's chat history using OpenAI format."""
    db = load_user_database()
    profile = db.get('users', {}).get(user_id)
    if profile:
        if 'chat_history' not in profile or not isinstance(profile['chat_history'], list): profile['chat_history'] = []
        if role not in ['user', 'assistant', 'system', 'tool']:
            logger.warning(f"Invalid role '{role}' provided for chat message."); return profile
        # Allow None content for assistant (tool calls) and stringify tool content if needed
        if role == 'tool' and content is not None and not isinstance(content, str):
             content = json.dumps(content)
        elif role == 'assistant' and content is None:
             content = "" # Store empty string instead of None for assistant text content
        elif not content and role == 'user':
             logger.warning(f"Empty content provided for chat role 'user'. Skipping save."); #return profile # Skip saving empty user messages

        chat_message = {"role": role, "content": content, "timestamp": datetime.now().isoformat()}
        profile['chat_history'].append(chat_message)
        # Limit history
        max_history = 50
        if len(profile['chat_history']) > max_history:
             system_msgs = [m for m in profile['chat_history'] if m['role'] == 'system']
             other_msgs = [m for m in profile['chat_history'] if m['role'] != 'system']
             profile['chat_history'] = system_msgs + other_msgs[-max_history:]
        save_user_database(db)
        return profile
    return None


# --- Basic Routine Fallback Function ---
def generate_basic_routine(emotion, goal, available_time=60, days=7):
    """Generate a basic routine as fallback."""
    logger.info(f"Generating basic fallback routine for emotion={emotion}, goal={goal}")
    routine_types = {
        "job_search": [
            {"name": "Research Target Companies", "points": 15, "duration": 20, "description": "Identify 3 potential employers aligned with your goal."},
            {"name": "Update LinkedIn Section", "points": 15, "duration": 25, "description": "Refine one section of your LinkedIn profile (e.g., summary, experience)."},
            {"name": "Practice STAR Method", "points": 20, "duration": 15, "description": "Outline one experience using the STAR method for interviews."},
            {"name": "Find Networking Event", "points": 10, "duration": 10, "description": "Look for one relevant online or local networking event."}
        ],
        "skill_building": [
            {"name": "Online Tutorial (1 Module)", "points": 25, "duration": 45, "description": "Complete one module of a relevant online course/tutorial."},
            {"name": "Read Industry Blog/Article", "points": 10, "duration": 15, "description": "Read and summarize one article about trends in your field."},
            {"name": "Small Project Task", "points": 30, "duration": 60, "description": "Dedicate time to a specific task within a personal project."},
            {"name": "Review Skill Documentation", "points": 15, "duration": 30, "description": "Read documentation or examples for a skill you're learning."}
        ],
        "motivation_wellbeing": [
            {"name": "Mindful Reflection", "points": 10, "duration": 10, "description": "Spend 10 minutes reflecting on progress and challenges without judgment."},
            {"name": "Set 1-3 Daily Intentions", "points": 10, "duration": 5, "description": "Define small, achievable goals for the day."},
            {"name": "Short Break/Walk", "points": 15, "duration": 15, "description": "Take a brief break away from screens, preferably with light movement."},
            {"name": "Connect with Support", "points": 20, "duration": 20, "description": "Briefly chat with a friend, mentor, or peer about your journey."}
        ]
    }
    cleaned_emotion = emotion.split(" ")[0].lower() if " " in emotion else emotion.lower()
    negative_emotions = ["unmotivated", "anxious", "confused", "overwhelmed", "discouraged"]
    if "job" in goal.lower() or "internship" in goal.lower() or "company" in goal.lower(): base_type = "job_search"
    elif "skill" in goal.lower() or "learn" in goal.lower(): base_type = "skill_building"
    elif "network" in goal.lower(): base_type = "job_search"
    else: base_type = "skill_building"
    include_wellbeing = cleaned_emotion in negative_emotions
    daily_tasks_list = []
    for day in range(1, days + 1):
        day_tasks, remaining_time, tasks_added_count = [], available_time, 0
        possible_tasks = routine_types[base_type].copy()
        if include_wellbeing: possible_tasks.extend(routine_types["motivation_wellbeing"])
        random.shuffle(possible_tasks)
        for task in possible_tasks:
            if task["duration"] <= remaining_time and tasks_added_count < 3:
                day_tasks.append(task); remaining_time -= task["duration"]; tasks_added_count += 1
            if remaining_time < 10 or tasks_added_count >= 3: break
        daily_tasks_list.append({"day": day, "tasks": day_tasks})
    routine = {"name": f"{days}-Day Focus Plan", "description": f"A basic {days}-day plan focusing on '{goal}' while acknowledging feeling {cleaned_emotion}.", "days": days, "daily_tasks": daily_tasks_list}
    return routine

# --- Tool Implementation Functions ---
# (Keep generate_document_template, create_personalized_routine,
#  analyze_resume, analyze_portfolio, extract_and_rate_skills_from_resume - unchanged from previous corrected version)
# Note: get_job_opportunities function is now removed.

def generate_document_template(document_type: str, career_field: str = "", experience_level: str = "") -> str:
    """Generates a basic markdown template for the specified document type."""
    logger.info(f"Executing tool: generate_document_template(document_type='{document_type}', career_field='{career_field}', experience_level='{experience_level}')")
    template = f"## Basic Template: {document_type}\n\n"
    template += f"**Target Field:** {career_field or 'Not specified'}\n"
    template += f"**Experience Level:** {experience_level or 'Not specified'}\n\n---\n\n"
    if "resume" in document_type.lower():
         template += ("### Contact Information\n- Name:\n- Phone:\n- Email:\n- LinkedIn URL:\n- Portfolio URL (Optional):\n\n"
                      "### Summary/Objective\n_[ 2-3 sentences summarizing your key skills, experience, and career goals, tailored to the job/field. ]_\n\n"
                      "### Experience\n**Company Name** | Location | Job Title | _Start Date – End Date_\n- Accomplishment 1 (Use action verbs and quantify results, e.g., 'Increased sales by 15%...')\n- Accomplishment 2\n\n_[ Repeat for other relevant positions ]_\n\n"
                      "### Education\n**University/Institution Name** | Degree | _Graduation Date (or Expected)_\n- Relevant coursework, honors, activities (Optional)\n\n"
                      "### Skills\n- **Technical Skills:** [ e.g., Python, Java, SQL, MS Excel, Google Analytics ]\n- **Languages:** [ e.g., English (Native), Spanish (Fluent) ]\n- **Other:** [ Certifications, relevant tools ]\n")
    elif "cover letter" in document_type.lower():
         template += ("[Your Name]\n[Your Address]\n[Your Phone]\n[Your Email]\n\n"
                      "[Date]\n\n"
                      "[Hiring Manager Name (if known), or 'Hiring Team']\n[Hiring Manager Title (if known)]\n[Company Name]\n[Company Address]\n\n"
                      "**Subject: Application for [Job Title] Position - [Your Name]**\n\n"
                      "Dear [Mr./Ms./Mx. Last Name or Hiring Team],\n\n"
                      "**Introduction:** State the position you are applying for and where you saw the advertisement. Briefly express your enthusiasm for the role and the company. Mention 1-2 key qualifications that make you a strong fit.\n_[ Example: I am writing to express my strong interest in the [Job Title] position advertised on [Platform]. With my background in [Relevant Field] and proven ability to [Key Skill], I am confident I possess the skills and experience necessary to excel in this role and contribute significantly to [Company Name]. ]_\n\n"
                      "**Body Paragraph(s):** Elaborate on your qualifications and experiences, directly addressing the requirements listed in the job description. Provide specific examples (using the STAR method implicitly can be effective). Explain why you are interested in *this specific* company and role. Show you've done your research.\n_[ Example: In my previous role at [Previous Company], I was responsible for [Responsibility relevant to new job]. I successfully [Quantifiable achievement relevant to new job], demonstrating my ability to [Skill required by new job]. I am particularly drawn to [Company Name]'s work in [Specific area company works in], as described in [Source, e.g., recent news, company website], and I believe my [Relevant skill/experience] would be a valuable asset to your team. ]_\n\n"
                      "**Conclusion:** Reiterate your strong interest and suitability for the role. Briefly summarize your key strengths. State your call to action (e.g., "I am eager to discuss my qualifications further..."). Thank the reader for their time and consideration.\n_[ Example: Thank you for considering my application. My resume provides further detail on my qualifications. I am excited about the opportunity to contribute to [Company Name] and look forward to hearing from you soon. ]_\n\n"
                      "Sincerely,\n\n[Your Typed Name]")
    elif "linkedin summary" in document_type.lower():
         template += ("### LinkedIn Summary/About Section Template\n\n"
                      "**Headline:** [ A concise, keyword-rich description of your professional identity, e.g., 'Software Engineer specializing in AI | Python | Cloud Computing | Seeking Innovative Opportunities' ]\n\n"
                      "**About Section:**\n"
                      "_[ Paragraph 1: Hook & Overview. Start with a compelling statement about your passion, expertise, or career mission. Briefly introduce who you are professionally and your main areas of focus. Use keywords relevant to your field and desired roles. ]_\n\n"
                      "_[ Paragraph 2: Key Skills & Experience Highlights. Detail your core competencies and technical/soft skills. Mention key experiences or types of projects you've worked on. Quantify achievements where possible. Tailor this to the audience you want to attract (recruiters, clients, peers). ]_\n\n"
                      "_[ Paragraph 3: Career Goals & What You're Seeking (Optional but recommended). Briefly state your career aspirations or the types of opportunities, connections, or collaborations you are looking for. ]_\n\n"
                      "_[ Paragraph 4: Call to Action / Personality (Optional). You might end with an invitation to connect, mention personal interests related to your field, or add a touch of personality. ]_\n\n"
                      "**Specialties/Keywords:** [ List 5-10 key terms related to your skills and industry, e.g., Project Management, Data Analysis, Agile Methodologies, Content Strategy, Java, Cloud Security ]")
    else:
         template += "_[ Basic structure for this document type will be provided here. ]_"

    # Return as JSON string, even though AI might generate markdown directly
    return json.dumps({"template_markdown": template})


def create_personalized_routine(emotion: str, goal: str, available_time_minutes: int = 60, routine_length_days: int = 7) -> str:
    """Creates a personalized routine, falling back to basic generation if needed."""
    logger.info(f"Executing tool: create_personalized_routine(emotion='{emotion}', goal='{goal}', time={available_time_minutes}, days={routine_length_days})")
    try:
        logger.warning("create_personalized_routine tool is using the basic fallback generation.")
        routine = generate_basic_routine(emotion, goal, available_time_minutes, routine_length_days)
        if not routine: raise ValueError("Basic routine generation failed.")
        logger.info(f"Generated routine: {routine.get('name', 'Unnamed Routine')}")
        return json.dumps(routine)
    except Exception as e:
        logger.error(f"Error in create_personalized_routine tool: {e}")
        try: # Attempt fallback again
            routine = generate_basic_routine(emotion, goal, available_time_minutes, routine_length_days)
            return json.dumps(routine) if routine else json.dumps({"error": "Failed to generate routine."})
        except Exception as fallback_e:
             logger.error(f"Fallback routine generation also failed: {fallback_e}")
             return json.dumps({"error": f"Failed to generate routine: {e}"})


def analyze_resume(resume_text: str, career_goal: str) -> str:
    """Provides analysis of the resume using AI (Simulated)."""
    logger.info(f"Executing tool: analyze_resume(career_goal='{career_goal}', resume_length={len(resume_text)})")
    logger.warning("analyze_resume tool is using placeholder analysis.")
    analysis = { "analysis": { "strengths": ["Placeholder: Clear objective/summary.", "Placeholder: Good use of action verbs."], "areas_for_improvement": ["Placeholder: Quantify achievements more.", f"Placeholder: Tailor skills section better for '{career_goal}'."], "format_feedback": "Placeholder: Overall format is clean, but consider standardizing date formats.", "content_feedback": f"Placeholder: Experience seems partially relevant to '{career_goal}', but highlight transferable skills.", "keyword_suggestions": ["Placeholder: Add keywords like 'Keyword1', 'Keyword2' relevant to goal."], "next_steps": ["Placeholder: Refine descriptions for last 2 roles.", "Placeholder: Add a project section if applicable."] } }
    return json.dumps(analysis)

def analyze_portfolio(portfolio_description: str, career_goal: str, portfolio_url: str = "") -> str:
    """Provides analysis of the portfolio using AI (Simulated)."""
    logger.info(f"Executing tool: analyze_portfolio(career_goal='{career_goal}', url='{portfolio_url}', desc_length={len(portfolio_description)})")
    logger.warning("analyze_portfolio tool is using placeholder analysis.")
    analysis = { "analysis": { "alignment_with_goal": f"Placeholder: Portfolio description suggests moderate alignment with '{career_goal}'.", "strengths": ["Placeholder: Variety of projects mentioned.", "Placeholder: Clear description provided."], "areas_for_improvement": ["Placeholder: Ensure project descriptions explicitly link to skills needed for the goal.", "Placeholder: Consider adding testimonials or case study depth."], "presentation_feedback": f"Placeholder: If URL ({portfolio_url}) provided, check for mobile responsiveness and clear navigation (visual analysis needed). Based on description, sounds organized.", "next_steps": ["Placeholder: Select 2-3 best projects strongly related to the goal and feature them prominently.", "Placeholder: Get feedback from peers in the target field."] } }
    return json.dumps(analysis)

def extract_and_rate_skills_from_resume(resume_text: str, max_skills: int = 8) -> str:
    """Extracts and rates skills from resume text (Simulated)."""
    logger.info(f"Executing tool: extract_and_rate_skills_from_resume(resume_length={len(resume_text)}, max_skills={max_skills})")
    logger.warning("extract_and_rate_skills_from_resume tool is using placeholder extraction.")
    possible_skills = ["Python", "Java", "JavaScript", "Project Management", "Communication", "Data Analysis", "Teamwork", "Leadership", "SQL", "React", "Customer Service", "Problem Solving", "Cloud Computing (AWS/Azure/GCP)", "Agile Methodologies", "Machine Learning"]
    found_skills = []
    resume_lower = resume_text.lower()
    for skill in possible_skills:
        if re.search(r'\b' + re.escape(skill.lower()) + r'\b', resume_lower):
            found_skills.append({"name": skill, "score": random.randint(4, 9)})
        if len(found_skills) >= max_skills: break
    if not found_skills and len(resume_text) > 50:
        found_skills = [ {"name": "Communication", "score": random.randint(5,8)}, {"name": "Teamwork", "score": random.randint(5,8)}, {"name": "Problem Solving", "score": random.randint(5,8)}, ]
    logger.info(f"Extracted skills (placeholder): {[s['name'] for s in found_skills]}")
    return json.dumps({"skills": found_skills[:max_skills]})


# --- AI Interaction Logic (Using OpenAI) ---
def get_ai_response(user_id: str, user_input: str, generate_recommendations: bool = True) -> str:
    """Gets response from OpenAI, handling context, system prompt, and tool calls."""
    logger.info(f"Getting AI response for user {user_id}. Input: '{user_input[:100]}...'")
    if not client:
        return "I apologize, the AI service is currently unavailable. Please check the configuration."

    try:
        user_profile = get_user_profile(user_id)
        if not user_profile:
             logger.error(f"Failed to retrieve profile for user {user_id}.")
             return "Sorry, I couldn't access your profile information right now."

        current_emotion_display = user_profile.get('current_emotion', 'Not specified')
        # --- System Prompt Updated ---
        system_prompt = f"""
        You are Aishura, an emotionally intelligent AI career assistant. Your primary goal is to provide empathetic, realistic, and actionable career guidance. Always follow these steps:
        1.  Acknowledge the user's message and, if applicable, their expressed emotion (e.g., "I understand you're feeling {current_emotion_display}..."). Use empathetic language.
        2.  Directly address the user's query or statement.
        3.  Proactively offer relevant support using your available tools: suggest generating document templates (`generate_document_template`), creating a personalized routine (`create_personalized_routine`), analyzing their resume (`analyze_resume`) or portfolio (`analyze_portfolio`) if appropriate or if they mention them.
        4.  **Job Suggestions:** If the user asks for job opportunities or related help, **do not use a tool**. Instead, generate 2-3 plausible job titles/roles based on their stated main goal ('{user_profile.get('career_goal', 'Not specified')}') and location ('{user_profile.get('location', 'Not specified')}'). If they have provided a resume (path: '{user_profile.get('resume_path', '')}'), mention how their skills might align with these roles. Keep suggestions general and indicate they are examples, not live listings.
        5.  Tailor your response based on the user's profile: Name: {user_profile.get('name', 'User')}, Location: {user_profile.get('location', 'Not specified')}, Goal: {user_profile.get('career_goal', 'Not specified')}.
        6.  If the user has uploaded a resume or portfolio (check paths above), mention you can analyze them or reference previous analysis if relevant.
        7.  Keep responses concise, friendly, and focused on next steps. Use markdown for formatting.
        8.  If a tool call fails, inform the user gracefully (e.g., "I couldn't generate the template right now...") and suggest alternatives. Do not show raw error messages.
        """

        # --- Build Message History ---
        messages = [{"role": "system", "content": system_prompt}]
        chat_history = user_profile.get('chat_history', [])
        for msg in chat_history:
             if isinstance(msg, dict) and 'role' in msg and 'content' in msg:
                  # Handle potential None content for assistant messages (tool calls)
                  content = msg['content'] if msg['content'] is not None else ""
                  messages.append({"role": msg['role'], "content": content})
             elif isinstance(msg, dict) and msg.get('role') == 'tool' and all(k in msg for k in ['tool_call_id', 'name', 'content']):
                 # Content for tool role must be a string
                 tool_content = msg['content'] if isinstance(msg['content'], str) else json.dumps(msg['content'])
                 messages.append({ "role": "tool", "tool_call_id": msg['tool_call_id'], "name": msg['name'], "content": tool_content })

        messages.append({"role": "user", "content": user_input})

        # --- Initial API Call ---
        logger.info(f"Sending {len(messages)} messages to OpenAI model {MODEL_ID}.")
        response = client.chat.completions.create(
            model=MODEL_ID,
            messages=messages,
            tools=tools_list, # Provide available tools (excluding job search)
            tool_choice="auto",
            temperature=0.7,
            max_tokens=1500
        )
        response_message = response.choices[0].message

        # --- Log Assistant's Turn (Potentially with Tool Calls) ---
        # Store the assistant's message regardless of whether it contains text or tool calls.
        # The 'content' might be None/empty if only tool calls are made.
        assistant_response_for_db = {
            "role": "assistant",
            "content": response_message.content, # Store text content (can be None)
             # Add tool calls if they exist, for accurate history reconstruction
            "tool_calls": [tc.model_dump() for tc in response_message.tool_calls] if response_message.tool_calls else None
        }
        # Don't save yet, save *after* potential second call

        final_response_content = response_message.content # Initial text response
        tool_calls = response_message.tool_calls

        # --- Tool Call Handling ---
        if tool_calls:
            logger.info(f"AI requested {len(tool_calls)} tool call(s): {[tc.function.name for tc in tool_calls]}")
            # Append the assistant's response message that contains the tool calls to the *local* messages list for the next API call
            messages.append(response_message)

            available_functions = {
                "generate_document_template": generate_document_template,
                "create_personalized_routine": create_personalized_routine,
                "analyze_resume": analyze_resume,
                "analyze_portfolio": analyze_portfolio,
                "extract_and_rate_skills_from_resume": extract_and_rate_skills_from_resume,
            }

            tool_results_for_api = [] # Collect results to append for the next API call
            tool_results_for_db = [] # Collect results for database storage

            for tool_call in tool_calls:
                function_name = tool_call.function.name
                function_to_call = available_functions.get(function_name)
                try:
                    function_args = json.loads(tool_call.function.arguments)
                    if function_to_call:
                        # --- Special Handling & File Saving ---
                        if function_name == "analyze_resume":
                             if 'career_goal' not in function_args: function_args['career_goal'] = user_profile.get('career_goal', 'Not specified')
                             save_user_resume(user_id, function_args.get('resume_text', ''))
                        if function_name == "analyze_portfolio":
                             if 'career_goal' not in function_args: function_args['career_goal'] = user_profile.get('career_goal', 'Not specified')
                             save_user_portfolio(user_id, function_args.get('portfolio_url', ''), function_args.get('portfolio_description', ''))
                        # --- Call Function ---
                        logger.info(f"Calling function '{function_name}' with args: {function_args}")
                        function_response = function_to_call(**function_args) # Response should be JSON string
                        logger.info(f"Function '{function_name}' returned: {function_response[:200]}...")
                        tool_result = { "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": function_response }
                    else:
                        logger.warning(f"Function {function_name} requested by AI but not implemented.")
                        tool_result = { "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": json.dumps({"error": f"Tool '{function_name}' is not available."}) }
                except json.JSONDecodeError as e:
                     logger.error(f"Error decoding arguments for {function_name}: {tool_call.function.arguments} - {e}")
                     tool_result = { "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": json.dumps({"error": f"Invalid arguments provided for tool {function_name}."}) }
                except Exception as e:
                    logger.exception(f"Error executing function {function_name}: {e}")
                    tool_result = { "tool_call_id": tool_call.id, "role": "tool", "name": function_name, "content": json.dumps({"error": f"Failed to execute tool {function_name}."}) }

                # Append result for both next API call and DB storage
                messages.append(tool_result) # Append full dict to local messages for API
                tool_results_for_db.append(tool_result) # Store for DB

            # --- Second API Call (after tool execution) ---
            logger.info(f"Sending {len(messages)} messages to OpenAI (including tool results).")
            second_response = client.chat.completions.create(
                model=MODEL_ID, messages=messages, temperature=0.7, max_tokens=1500
            )
            final_response_content = second_response.choices[0].message.content
            logger.info("Received final response from OpenAI after tool calls.")

            # --- Store User Input, Assistant (Tool Call) Message, Tool Results, and Final Assistant Response ---
            add_chat_message(user_id, "user", user_input)
            # Store the *first* assistant message (which contained the tool call request)
            add_chat_message(user_id, "assistant", assistant_response_for_db)
            # Store the tool results
            for res in tool_results_for_db: add_chat_message(user_id, "tool", res)
            # Store the *final* assistant text response
            add_chat_message(user_id, "assistant", {"role": "assistant", "content": final_response_content})

        else:
            # --- No Tool Calls ---
            logger.info("No tool calls requested by AI.")
            # Store User Input and Assistant Response
            add_chat_message(user_id, "user", user_input)
            # Ensure the response content is stored correctly (might be None initially)
            add_chat_message(user_id, "assistant", {"role": "assistant", "content": final_response_content if final_response_content else ""})


        # --- Post-processing and Return ---
        if not final_response_content:
             final_response_content = "I've processed that. Is there anything else I can help you with?"
             logger.warning("AI returned empty content after processing.")

        # Optional: Generate recommendations based on the final interaction (can be slow)
        if generate_recommendations:
            try:
                 # Consider making this async or optional via UI button
                 # gen_recommendations_openai(user_id, user_input, final_response_content if final_response_content else "Tool action completed.")
                 pass # Skipping inline recommendation generation for performance
            except Exception as rec_e:
                 logger.error(f"Error during recommendation generation: {rec_e}")


        return final_response_content if final_response_content else "Action completed."

    except openai.APIError as e:
        logger.error(f"OpenAI API Error: {e.status_code} - {e.response}")
        return f"I'm sorry, there was an issue communicating with the AI service (Code: {e.status_code}). Please try again."
    except openai.APITimeoutError:
        logger.error("OpenAI API request timed out.")
        return "I'm sorry, the request to the AI service timed out. Please try again."
    except openai.APIConnectionError as e:
        logger.error(f"OpenAI Connection Error: {e}")
        return "I couldn't connect to the AI service. Please check your network connection."
    except openai.RateLimitError:
        logger.error("OpenAI Rate Limit Exceeded.")
        return "I'm experiencing high demand right now. Please try again in a moment."
    except Exception as e:
        logger.exception(f"Unexpected error in get_ai_response for user {user_id}: {e}")
        return "I apologize, but an unexpected error occurred. Please try restarting the conversation or try again later."


# --- Recommendation Generation (Placeholder - Adapt for OpenAI) ---
def gen_recommendations_openai(user_id, user_input, ai_response):
    """Generate recommendations using OpenAI."""
    logger.info(f"Generating recommendations for user {user_id}")
    if not client: return []
    try:
        user_profile = get_user_profile(user_id)
        prompt = f"""
        Based on the user profile and recent conversation, generate 1-3 specific, actionable recommendations for their next steps. Focus on practical actions.

        User Profile: Emotion: {user_profile.get('current_emotion', 'N/A')}, Goal: {user_profile.get('career_goal', 'N/A')}, Location: {user_profile.get('location', 'N/A')}
        Recent Interaction: User: {user_input} | AI: {ai_response}

        Generate recommendations in this JSON format ONLY (a list of objects):
        ```json
        [
          {{"title": "Concise title", "description": "Detailed explanation (2-3 sentences).", "action_type": "skill_building | networking | resume_update | portfolio_review | interview_prep | mindset_shift | other", "priority": "high | medium | low"}}
        ]
        ```
        """
        response = client.chat.completions.create(
            model=MODEL_ID,
            messages=[ {"role": "system", "content": "You generate career recommendations in JSON list format."}, {"role": "user", "content": prompt} ],
            temperature=0.5, max_tokens=512,
            # Attempting JSON mode, but ensure the prompt clearly asks for the list format
            # response_format={"type": "json_object"} # This might force an outer object, adjust parsing if used.
        )
        json_str = response.choices[0].message.content
        logger.info(f"Raw recommendations JSON string: {json_str}")
        try:
            # Clean potential markdown fences
            if json_str.startswith("```json"): json_str = json_str.split("```json")[1].split("```")[0].strip()
            recommendations = json.loads(json_str)
            if not isinstance(recommendations, list): # Handle if AI wraps in an object
                 if isinstance(recommendations, dict) and len(recommendations) == 1:
                      key = list(recommendations.keys())[0]
                      if isinstance(recommendations[key], list):
                           recommendations = recommendations[key]
                      else: raise ValueError("JSON is not a list or expected object wrapper.")
                 else: raise ValueError("JSON is not a list.")

            valid_recs_added = 0
            for rec in recommendations:
                 if isinstance(rec, dict) and all(k in rec for k in ['title', 'description', 'action_type', 'priority']):
                     add_recommendation_to_user(user_id, rec); valid_recs_added += 1
                 else: logger.warning(f"Skipping invalid recommendation format: {rec}")
            logger.info(f"Added {valid_recs_added} recommendations.")
            return recommendations
        except (json.JSONDecodeError, ValueError) as e:
            logger.error(f"Failed to parse JSON recommendations: {e}\nResponse: {json_str}"); return []
    except Exception as e: logger.exception(f"Error generating recommendations: {e}"); return []


# --- Chart and Visualization Functions ---
def create_emotion_chart(user_id):
    """Create a chart of user's emotions over time"""
    user_profile = get_user_profile(user_id)
    emotion_records = user_profile.get('daily_emotions', [])
    if not emotion_records:
        fig = go.Figure(); fig.add_annotation(text="No emotion data tracked yet.", showarrow=False); fig.update_layout(title="Emotion Tracking"); return fig
    emotion_values = {"Unmotivated": 1, "Anxious": 2, "Confused": 3, "Discouraged": 4, "Overwhelmed": 5, "Excited": 6}
    dates = [datetime.fromisoformat(record['date']) for record in emotion_records]
    emotion_scores = [emotion_values.get(record['emotion'], 3) for record in emotion_records]
    emotion_names = [record['emotion'] for record in emotion_records]
    df = pd.DataFrame({'Date': dates, 'Emotion Score': emotion_scores, 'Emotion': emotion_names}).sort_values('Date')
    fig = px.line(df, x='Date', y='Emotion Score', markers=True, labels={"Emotion Score": "Emotional State"}, title="Your Emotional Journey")
    fig.update_traces(hovertemplate='%{x|%Y-%m-%d %H:%M}<br>Feeling: %{text}', text=df['Emotion'])
    fig.update_yaxes(tickvals=list(emotion_values.values()), ticktext=list(emotion_values.keys()))
    return fig

def create_progress_chart(user_id):
    """Create a chart showing user's progress points over time"""
    user_profile = get_user_profile(user_id)
    tasks = user_profile.get('completed_tasks', [])
    if not tasks:
        fig = go.Figure(); fig.add_annotation(text="No tasks completed yet.", showarrow=False); fig.update_layout(title="Progress Tracking"); return fig
    tasks.sort(key=lambda x: datetime.fromisoformat(x['date']))
    dates, points_timeline, task_labels, cumulative_points = [], [], [], 0
    points_per_task = 20 # Default points if not stored
    for task in tasks:
        dates.append(datetime.fromisoformat(task['date']))
        # Use actual profile points for timeline if available and reliable
        # For simplicity, recalculate cumulative based on tasks for chart
        cumulative_points += task.get('points', points_per_task) # Use points stored with task if they existed
        points_timeline.append(cumulative_points)
        task_labels.append(task['task'])
    df = pd.DataFrame({'Date': dates, 'Points': points_timeline, 'Task': task_labels})
    fig = px.line(df, x='Date', y='Points', markers=True, title="Your Career Journey Progress")
    fig.update_traces(hovertemplate='%{x|%Y-%m-%d %H:%M}<br>Points: %{y}<br>Completed: %{text}', text=df['Task'])
    return fig

def create_routine_completion_gauge(user_id):
    """Create a gauge chart showing routine completion percentage"""
    user_profile = get_user_profile(user_id)
    routines = user_profile.get('routine_history', [])
    if not routines:
        fig = go.Figure(go.Indicator(mode="gauge", value=0, title={'text': "Routine Completion"}))
        fig.add_annotation(text="No active routine.", showarrow=False); return fig
    latest_routine = routines[0] # Assuming latest is first
    completion = latest_routine.get('completion', 0)
    routine_name = latest_routine.get('routine', {}).get('name', 'Current Routine')
    fig = go.Figure(go.Indicator(
        mode = "gauge+number", value = completion, domain = {'x': [0, 1], 'y': [0, 1]},
        title = {'text': f"{routine_name} Completion (%)"},
        gauge = {'axis': {'range': [0, 100], 'tickwidth': 1, 'tickcolor': "darkblue"},
                 'bar': {'color': "cornflowerblue"}, 'bgcolor': "white", 'borderwidth': 2, 'bordercolor': "gray",
                 'steps': [{'range': [0, 50], 'color': 'whitesmoke'}, {'range': [50, 80], 'color': 'lightgray'}],
                 'threshold': {'line': {'color': "green", 'width': 4}, 'thickness': 0.75, 'value': 90}}))
    return fig

def create_skill_radar_chart(user_id):
    """Creates a radar chart of user's skills based on resume analysis."""
    logger.info(f"Creating skill radar chart for user {user_id}")
    user_profile = get_user_profile(user_id)
    resume_path = user_profile.get('resume_path')
    if not resume_path or not os.path.exists(resume_path):
        logger.warning("No resume path found or file missing for skill chart.")
        fig = go.Figure(); fig.add_annotation(text="Upload & Analyze Resume for Skill Chart", showarrow=False); fig.update_layout(title="Skill Assessment"); return fig
    try:
        with open(resume_path, 'r', encoding='utf-8') as f: resume_text = f.read()
        # Use the tool function to extract skills (simulated call here)
        skills_json_str = extract_and_rate_skills_from_resume(resume_text=resume_text)
        skill_data = json.loads(skills_json_str)
        if 'skills' in skill_data and skill_data['skills']:
            skills = skill_data['skills'][:8] # Limit skills
            categories = [skill['name'] for skill in skills]
            values = [skill['score'] for skill in skills]
            if len(categories) > 2: categories.append(categories[0]); values.append(values[0]) # Close loop
            fig = go.Figure()
            fig.add_trace(go.Scatterpolar(r=values, theta=categories, fill='toself', name='Skills'))
            fig.update_layout(polar=dict(radialaxis=dict(visible=True, range=[0, 10])), showlegend=False, title="Skill Assessment (Based on Resume)")
            logger.info(f"Successfully created radar chart with {len(skills)} skills.")
            return fig
        else:
            logger.warning("Could not extract skills from resume for chart.")
            fig = go.Figure(); fig.add_annotation(text="Could not extract skills from resume", showarrow=False); fig.update_layout(title="Skill Assessment"); return fig
    except Exception as e:
        logger.exception(f"Error creating skill radar chart: {e}")
        fig = go.Figure(); fig.add_annotation(text="Error analyzing skills", showarrow=False); fig.update_layout(title="Skill Assessment"); return fig

# --- Gradio Interface Components ---
def create_interface():
    """Create the Gradio interface for Aishura"""
    session_user_id = str(uuid.uuid4())
    logger.info(f"Initializing Gradio interface for session user ID: {session_user_id}")
    get_user_profile(session_user_id) # Initialize profile

    # --- Event Handlers ---
    def welcome(name, location, emotion, goal):
        """Handles welcome screen submission."""
        logger.info(f"Welcome action: name='{name}', loc='{location}', emo='{emotion}', goal='{goal}'")
        if not all([name, location, emotion, goal]):
            return ("Please fill out all fields.", gr.update(visible=True), gr.update(visible=False)) # Keep welcome visible
        # Clean goal string if it includes emoji
        cleaned_goal = goal.rsplit(" ", 1)[0] if goal[-1].isnumeric() == False and goal[-2] == " " else goal # Basic emoji removal
        update_user_profile(session_user_id, {"name": name, "location": location, "career_goal": cleaned_goal}) # Store cleaned goal
        add_emotion_record(session_user_id, emotion)
        initial_input = f"Hi Aishura! I'm {name} from {location}. I'm feeling {emotion}, and my main goal is '{cleaned_goal}'. Can you help me get started?"
        ai_response = get_ai_response(session_user_id, initial_input, generate_recommendations=True)
        initial_chat = [{"role":"user", "content": initial_input}, {"role":"assistant", "content": ai_response}] # Use messages format
        # Fetch initial charts
        emotion_fig = create_emotion_chart(session_user_id)
        progress_fig = create_progress_chart(session_user_id)
        routine_fig = create_routine_completion_gauge(session_user_id)
        skill_fig = create_skill_radar_chart(session_user_id)
        # Return updates: chatbot history, visibility, and chart values
        return (gr.update(value=initial_chat), # Chatbot expects list of dicts
                gr.update(visible=False), gr.update(visible=True), # Show/hide groups
                gr.update(value=emotion_fig), gr.update(value=progress_fig), # Update plots with value=figure
                gr.update(value=routine_fig), gr.update(value=skill_fig))

    def chat_submit(message_text, history_list_dicts):
        """Handles sending a message in the chatbot (using messages format)."""
        logger.info(f"Chat submit: '{message_text[:50]}...'")
        if not message_text: return history_list_dicts, "", gr.update() # Return current history if empty input

        # Append user message to the history list
        history_list_dicts.append({"role": "user", "content": message_text})

        # Get AI response (which also saves interaction to DB)
        ai_response_text = get_ai_response(session_user_id, message_text, generate_recommendations=True)

        # Append AI response to the history list
        history_list_dicts.append({"role": "assistant", "content": ai_response_text})

        # Update recommendations display
        recommendations_md = display_recommendations(session_user_id)

        # Return updated history list, clear input box, update recommendations display
        return history_list_dicts, "", gr.update(value=recommendations_md)

    # --- Tool Interface Handlers ---
    # Removed search_jobs_interface_handler
    def generate_template_interface_handler(doc_type, career_field, experience):
        logger.info(f"Manual Template UI: type='{doc_type}', field='{career_field}', exp='{experience}'")
        template_json_str = generate_document_template(doc_type, career_field, experience)
        try:
            template_data = json.loads(template_json_str); return template_data.get('template_markdown', "Error.")
        except: return "Error displaying template."

    def create_routine_interface_handler(emotion, goal, time_available, days):
        logger.info(f"Manual Routine UI: emo='{emotion}', goal='{goal}', time='{time_available}', days='{days}'")
        # Clean emotion string
        cleaned_emotion = emotion.split(" ")[0] if " " in emotion else emotion
        routine_json_str = create_personalized_routine(cleaned_emotion, goal, int(time_available), int(days))
        try:
            routine_data = json.loads(routine_json_str)
            if "error" in routine_data: return f"Error: {routine_data['error']}", gr.update()
            add_routine_to_user(session_user_id, routine_data) # Save routine
            output_md = f"# Your {routine_data.get('name', 'Personalized Routine')}\n\n{routine_data.get('description', '')}\n\n"
            for day_plan in routine_data.get('daily_tasks', []):
                output_md += f"## Day {day_plan.get('day', '?')}\n"
                tasks = day_plan.get('tasks', [])
                if not tasks: output_md += "- Rest day or free choice.\n"
                else:
                    for task in tasks:
                        output_md += f"- **{task.get('name', 'Task')}** ({task.get('duration', '?')} mins)\n  *Why: {task.get('description', '...') }*\n" # Simplified display
                output_md += "\n"
            gauge_fig = create_routine_completion_gauge(session_user_id)
            return output_md, gr.update(value=gauge_fig)
        except: return "Error displaying routine.", gr.update()

    def analyze_resume_interface_handler(resume_text):
        logger.info(f"Manual Resume Analysis UI: length={len(resume_text)}")
        if not resume_text: return "Please paste your resume text.", gr.update(value=None)
        user_profile = get_user_profile(session_user_id)
        career_goal = user_profile.get('career_goal', 'Not specified')
        save_user_resume(session_user_id, resume_text) # Save first
        analysis_json_str = analyze_resume(resume_text, career_goal) # Call tool (placeholder analysis)
        try:
            analysis_data = json.loads(analysis_json_str).get('analysis', {})
            output_md = "## Resume Analysis Results (Simulated)\n\n" # Indicate simulation
            output_md += f"**Analysis vs Goal:** '{career_goal}'\n\n"
            output_md += "**Strengths:**\n" + "\n".join([f"- {s}" for s in analysis_data.get('strengths', [])]) + "\n\n"
            output_md += "**Areas for Improvement:**\n" + "\n".join([f"- {s}" for s in analysis_data.get('areas_for_improvement', [])]) + "\n\n"
            output_md += f"**Format Feedback:** {analysis_data.get('format_feedback', 'N/A')}\n"
            output_md += f"**Content Feedback:** {analysis_data.get('content_feedback', 'N/A')}\n"
            output_md += f"**Keyword Suggestions:** {', '.join(analysis_data.get('keyword_suggestions', []))}\n\n"
            output_md += "**Next Steps:**\n" + "\n".join([f"- {s}" for s in analysis_data.get('next_steps', [])])
            skill_fig = create_skill_radar_chart(session_user_id) # Update skill chart
            return output_md, gr.update(value=skill_fig)
        except: return "Error displaying analysis.", gr.update(value=None)

    def analyze_portfolio_interface_handler(portfolio_url, portfolio_description):
        logger.info(f"Manual Portfolio Analysis UI: url='{portfolio_url}', desc_len={len(portfolio_description)}")
        if not portfolio_description: return "Please provide a description."
        user_profile = get_user_profile(session_user_id)
        career_goal = user_profile.get('career_goal', 'Not specified')
        save_user_portfolio(session_user_id, portfolio_url, portfolio_description) # Save first
        analysis_json_str = analyze_portfolio(portfolio_description, career_goal, portfolio_url) # Call tool (placeholder analysis)
        try:
            analysis_data = json.loads(analysis_json_str).get('analysis', {})
            output_md = "## Portfolio Analysis Results (Simulated)\n\n" # Indicate simulation
            output_md += f"**Analysis vs Goal:** '{career_goal}'\n"
            if portfolio_url: output_md += f"**URL:** {portfolio_url}\n\n"
            output_md += f"**Alignment:** {analysis_data.get('alignment_with_goal', 'N/A')}\n\n"
            output_md += "**Strengths:**\n" + "\n".join([f"- {s}" for s in analysis_data.get('strengths', [])]) + "\n\n"
            output_md += "**Areas for Improvement:**\n" + "\n".join([f"- {s}" for s in analysis_data.get('areas_for_improvement', [])]) + "\n\n"
            output_md += f"**Presentation Feedback:** {analysis_data.get('presentation_feedback', 'N/A')}\n\n"
            output_md += "**Next Steps:**\n" + "\n".join([f"- {s}" for s in analysis_data.get('next_steps', [])])
            return output_md
        except: return "Error displaying analysis."

    # --- Progress Tracking Handlers ---
    def complete_task_handler(task_name):
        logger.info(f"Complete Task UI: task='{task_name}'")
        if not task_name: return ("Enter task name.", "", gr.update(), gr.update(), gr.update())
        add_task_to_user(session_user_id, task_name)
        # Update completion % of latest routine
        db = load_user_database(); profile = db.get('users', {}).get(session_user_id)
        if profile and profile.get('routine_history'):
            latest_routine_entry = profile['routine_history'][0]
            increment = random.randint(5, 15) # Simple increment
            new_completion = min(100, latest_routine_entry.get('completion', 0) + increment)
            latest_routine_entry['completion'] = new_completion; save_user_database(db)
        # Refresh charts
        emotion_fig = create_emotion_chart(session_user_id)
        progress_fig = create_progress_chart(session_user_id)
        gauge_fig = create_routine_completion_gauge(session_user_id)
        return (f"Great job on '{task_name}'!", "", gr.update(value=emotion_fig), gr.update(value=progress_fig), gr.update(value=gauge_fig))

    def update_emotion_handler(emotion):
        logger.info(f"Update Emotion UI: emotion='{emotion}'")
        if not emotion: return "Please select an emotion.", gr.update()
        add_emotion_record(session_user_id, emotion)
        emotion_fig = create_emotion_chart(session_user_id)
        # Clean emotion for display message
        cleaned_emotion_display = emotion.split(" ")[0] if " " in emotion else emotion
        return f"Emotion updated to '{cleaned_emotion_display}'.", gr.update(value=emotion_fig)

    def display_recommendations(current_user_id):
        """Fetches and formats recommendations."""
        logger.info(f"Displaying recommendations for user {current_user_id}")
        user_profile = get_user_profile(current_user_id)
        recommendations = user_profile.get('recommendations', [])
        if not recommendations: return "Chat with Aishura to get recommendations!"
        recent_recs = recommendations[:5] # Latest 5
        output_md = "# Your Latest Recommendations\n\n"
        if not recent_recs: return output_md + "No recommendations yet."
        for i, rec_entry in enumerate(recent_recs, 1):
            rec = rec_entry.get('recommendation', {})
            output_md += f"### {i}. {rec.get('title', 'N/A')}\n"
            output_md += f"{rec.get('description', 'N/A')}\n"
            output_md += f"**Priority:** {rec.get('priority', 'N/A').title()} | **Type:** {rec.get('action_type', 'N/A').replace('_', ' ').title()}\n---\n"
        return output_md

    # --- Build Gradio Interface ---
    with gr.Blocks(theme=gr.themes.Soft(primary_hue="blue", secondary_hue="sky")) as app:
        gr.Markdown("# Aishura - Your AI Career Assistant")

        # --- Welcome Screen ---
        with gr.Group(visible=True) as welcome_group:
            gr.Markdown("## Welcome to Aishura!")
            gr.Markdown("Let's get acquainted. Tell me a bit about yourself.")
            with gr.Row():
                with gr.Column():
                    name_input = gr.Textbox(label="Your Name", placeholder="e.g., Alex Chen")
                    location_input = gr.Textbox(label="Your Location", placeholder="e.g., London, UK")
                with gr.Column():
                    # Updated label and choices
                    emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="How are you feeling today?")
                    goal_dropdown = gr.Dropdown(choices=GOAL_TYPES, label="What's your main goal?") # Changed Label
            welcome_button = gr.Button("Start My Journey")
            welcome_output = gr.Markdown()

        # --- Main App Interface ---
        with gr.Group(visible=False) as main_interface:
            with gr.Tabs() as tabs:
                # --- Chat Tab ---
                with gr.TabItem("πŸ’¬ Chat"):
                    with gr.Row():
                        with gr.Column(scale=3):
                            # Corrected Chatbot initialization
                            chatbot = gr.Chatbot(
                                label="Aishura Assistant", height=550, type="messages", # Added type='messages'
                                avatar_images=("./user_avatar.png", "./aishura_avatar.png"),
                                show_copy_button=True
                                # Removed bubble_full_width
                            )
                            emotion_message_area = gr.Markdown("", visible=False, elem_classes="subtle-message")
                            msg_textbox = gr.Textbox(show_label=False, placeholder="Type your message...", container=False, scale=1)
                        with gr.Column(scale=1):
                            gr.Markdown("### ✨ Recommendations")
                            recommendation_output = gr.Markdown(value="Chat for recommendations.")
                            refresh_recs_button = gr.Button("πŸ”„ Refresh Recommendations")

                # --- Analysis Tab ---
                with gr.TabItem("πŸ“Š Analysis"):
                     with gr.Tabs() as analysis_subtabs:
                        with gr.TabItem("πŸ“„ Resume"):
                            gr.Markdown("### Resume Analysis")
                            gr.Markdown("Paste resume below for analysis against your goals.")
                            resume_text_input = gr.Textbox(label="Paste Resume Text Here", lines=15)
                            analyze_resume_button = gr.Button("Analyze My Resume")
                            resume_analysis_output = gr.Markdown()
                        with gr.TabItem("🎨 Portfolio"):
                            gr.Markdown("### Portfolio Analysis")
                            gr.Markdown("Provide link/description.")
                            portfolio_url_input = gr.Textbox(label="Portfolio URL (Optional)")
                            portfolio_desc_input = gr.Textbox(label="Portfolio Description", lines=5)
                            analyze_portfolio_button = gr.Button("Analyze My Portfolio")
                            portfolio_analysis_output = gr.Markdown()
                        with gr.TabItem("πŸ’‘ Skills"):
                             gr.Markdown("### Skill Assessment")
                             gr.Markdown("Visualize skills from resume analysis.")
                             skill_radar_chart_output = gr.Plot(label="Skill Radar Chart") # Corrected: Plot init

                # --- Tools Tab (Removed Job Search) ---
                with gr.TabItem("πŸ› οΈ Tools"):
                     with gr.Tabs() as tools_subtabs:
                        # Removed Job Search TabItem
                        with gr.TabItem("πŸ“ Templates"):
                             gr.Markdown("### Generate Document Templates")
                             gr.Markdown("Get started with career documents.")
                             doc_type_dropdown = gr.Dropdown(choices=["Resume", "Cover Letter", "LinkedIn Summary", "Networking Email"], label="Select Document Type")
                             doc_field_input = gr.Textbox(label="Career Field (Optional)")
                             doc_exp_dropdown = gr.Dropdown(choices=["Entry-Level", "Mid-Career", "Senior-Level", "Student/Intern"], label="Experience Level")
                             generate_template_button = gr.Button("Generate Template")
                             template_output_md = gr.Markdown()
                        with gr.TabItem("πŸ“… Routine"):
                             gr.Markdown("### Create a Personalized Routine")
                             gr.Markdown("Develop a plan tailored to your goals and feelings.")
                             routine_emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="How are you feeling?")
                             routine_goal_input = gr.Textbox(label="Specific Goal", placeholder="e.g., Apply to 5 jobs")
                             routine_time_slider = gr.Slider(minimum=15, maximum=120, value=45, step=15, label="Minutes/Day")
                             routine_days_slider = gr.Slider(minimum=3, maximum=21, value=7, step=1, label="Routine Length (Days)")
                             create_routine_button = gr.Button("Create My Routine")
                             routine_output_md = gr.Markdown()

                # --- Progress Tab ---
                with gr.TabItem("πŸ“ˆ Progress"):
                    gr.Markdown("## Track Your Journey")
                    with gr.Row():
                        with gr.Column(scale=1):
                            gr.Markdown("### Mark Task Complete"); task_input = gr.Textbox(label="Task Name"); complete_button = gr.Button("Complete Task"); task_output = gr.Markdown()
                            gr.Markdown("---"); gr.Markdown("### Update Emotion"); new_emotion_dropdown = gr.Dropdown(choices=EMOTIONS, label="How are you feeling now?"); emotion_button = gr.Button("Update Feeling"); emotion_output = gr.Markdown()
                        with gr.Column(scale=2):
                             gr.Markdown("### Visualizations")
                             with gr.Row(): emotion_chart_output = gr.Plot(label="Emotional Journey") # Corrected: Plot init
                             with gr.Row(): progress_chart_output = gr.Plot(label="Progress Points") # Corrected: Plot init
                             with gr.Row(): routine_gauge_output = gr.Plot(label="Routine Completion") # Corrected: Plot init

        # --- Event Wiring ---
        welcome_button.click(
            fn=welcome, inputs=[name_input, location_input, emotion_dropdown, goal_dropdown],
            outputs=[chatbot, welcome_group, main_interface, emotion_chart_output, progress_chart_output, routine_gauge_output, skill_radar_chart_output]
        )
        msg_textbox.submit( fn=chat_submit, inputs=[msg_textbox, chatbot], outputs=[chatbot, msg_textbox, recommendation_output] )
        refresh_recs_button.click( fn=lambda: display_recommendations(session_user_id), outputs=[recommendation_output] )
        # Analysis
        analyze_resume_button.click( fn=analyze_resume_interface_handler, inputs=[resume_text_input], outputs=[resume_analysis_output, skill_radar_chart_output] )
        analyze_portfolio_button.click( fn=analyze_portfolio_interface_handler, inputs=[portfolio_url_input, portfolio_desc_input], outputs=[portfolio_analysis_output] )
        # Tools
        generate_template_button.click( fn=generate_template_interface_handler, inputs=[doc_type_dropdown, doc_field_input, doc_exp_dropdown], outputs=[template_output_md] )
        create_routine_button.click( fn=create_routine_interface_handler, inputs=[routine_emotion_dropdown, routine_goal_input, routine_time_slider, routine_days_slider], outputs=[routine_output_md, routine_gauge_output] )
        # Progress
        complete_button.click( fn=complete_task_handler, inputs=[task_input], outputs=[task_output, task_input, emotion_chart_output, progress_chart_output, routine_gauge_output] )
        emotion_button.click( fn=update_emotion_handler, inputs=[new_emotion_dropdown], outputs=[emotion_output, emotion_chart_output] )

    return app

# --- Main Execution ---
if __name__ == "__main__":
    if not OPENAI_API_KEY:
        print("\n" + "*"*60)
        print(" Warning: OPENAI_API_KEY environment variable not found. ")
        print(" AI features require a valid OpenAI API key. ")
        print(" Create a '.env' file with: OPENAI_API_KEY=your_openai_key ")
        print("*"*60 + "\n")
        # Decide whether to exit or continue with limited functionality
        # exit(1)

    logger.info("Starting Aishura Gradio application...")
    aishura_app = create_interface()
    aishura_app.launch(share=False) # Set share=True for public link if needed
    logger.info("Aishura Gradio application stopped.")