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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
# from fastapi import FastAPI, HTTPException, BackgroundTasks
# from pydantic import BaseModel, EmailStr, Field
# from typing import Optional, Tuple
# from enum import Enum
# import os
# import base64
# import pickle
# import pandas as pd
# from dotenv import load_dotenv
# from langchain_openai import ChatOpenAI
# from langchain.schema import HumanMessage, SystemMessage
# from email.mime.text import MIMEText
# from google.auth.transport.requests import Request
# from google.oauth2.credentials import Credentials
# from google_auth_oauthlib.flow import InstalledAppFlow
# from googleapiclient.discovery import build
# from googleapiclient.errors import HttpError
# from datetime import datetime
# import json

# # Load environment variables (not needed on Hugging Face, but harmless)
# load_dotenv()

# # ------------------------------------------
# # Helper: Write GOOGLE_CREDENTIALS_JSON to file if needed
# # ------------------------------------------
# def ensure_credentials_file():
#     credentials_env = os.getenv("GOOGLE_CREDENTIALS_JSON")
#     credentials_path = "credentials_SYNAPSE.json"
#     if not os.path.exists(credentials_path):
#         if not credentials_env:
#             raise Exception("GOOGLE_CREDENTIALS_JSON not found in environment variables.")
#         try:
#             parsed_json = json.loads(credentials_env)
#         except json.JSONDecodeError:
#             raise Exception("Invalid JSON in GOOGLE_CREDENTIALS_JSON")
#         with open(credentials_path, "w") as f:
#             json.dump(parsed_json, f, indent=2)
#     return credentials_path

# # ------------------------------------------
# # FastAPI app
# # ------------------------------------------
# app = FastAPI(title="Recruitment Message Generator API", version="1.0.0")

# SCOPES = ["https://www.googleapis.com/auth/gmail.send"]
# openai_api_key = os.getenv("OPENAI_API_KEY")

# # ------------------------------------------
# # Enums and Models
# # ------------------------------------------
# class MessageType(str, Enum):
#     OUTREACH = "outreach"
#     INTRODUCTORY = "introductory"
#     FOLLOWUP = "followup"

# class GenerateMessageRequest(BaseModel):
#     job_evaluation: str
#     sender_email: EmailStr
#     reply_to_email: Optional[EmailStr] = Field(None, description="Recruiter's email for reply-to header")
#     recipient_email: EmailStr
#     candidate_name: str
#     current_role: str
#     current_company: str
#     company_name: str
#     role: str
#     recruiter_name: str
#     organisation: str
#     message_type: MessageType
#     send_email: bool = False

# class FeedbackRequest(BaseModel):
#     message: str
#     feedback: str

# class AuthenticateRequest(BaseModel):
#     email: EmailStr

# class AuthenticateResponse(BaseModel):
#     success: bool
#     message: str
#     error: Optional[str] = None

# class MessageResponse(BaseModel):
#     success: bool
#     message: str
#     email_sent: bool = False
#     email_subject: Optional[str] = None
#     error: Optional[str] = None

# # ------------------------------------------
# # Gmail Helper Functions
# # ------------------------------------------
# def get_token_file_path(email: str) -> str:
#     tokens_dir = "gmail_tokens"
#     if not os.path.exists(tokens_dir):
#         os.makedirs(tokens_dir)
#     safe_email = email.replace("@", "_at_").replace(".", "_dot_")
#     return os.path.join(tokens_dir, f"token_{safe_email}.pickle")

# def check_user_token_exists(email: str) -> bool:
#     token_file = get_token_file_path(email)
#     return os.path.exists(token_file)

# def load_user_credentials(email: str):
#     token_file = get_token_file_path(email)
#     if os.path.exists(token_file):
#         try:
#             with open(token_file, 'rb') as token:
#                 creds = pickle.load(token)
#                 return creds
#         except Exception:
#             if os.path.exists(token_file):
#                 os.remove(token_file)
#     return None

# def save_user_credentials(email: str, creds):
#     token_file = get_token_file_path(email)
#     with open(token_file, 'wb') as token:
#         pickle.dump(creds, token)

# def create_new_credentials(email: str):
#     credentials_path = ensure_credentials_file()
#     flow = InstalledAppFlow.from_client_secrets_file(
#         credentials_path, SCOPES
#     )
#     creds = flow.run_local_server(port=0)
#     save_user_credentials(email, creds)
#     return creds

# def authenticate_gmail(email: str, create_if_missing: bool = False):
#     creds = load_user_credentials(email)
#     if creds:
#         if creds.expired and creds.refresh_token:
#             try:
#                 creds.refresh(Request())
#                 save_user_credentials(email, creds)
#             except Exception:
#                 if create_if_missing:
#                     try:
#                         creds = create_new_credentials(email)
#                     except:
#                         return None
#                 else:
#                     return None
#         elif not creds.valid:
#             creds = None
#     if not creds:
#         if create_if_missing:
#             try:
#                 creds = create_new_credentials(email)
#             except:
#                 return None
#         else:
#             return None
#     try:
#         service = build("gmail", "v1", credentials=creds)
#         return service
#     except Exception:
#         return None

# def create_email_message(sender: str, to: str, subject: str, message_text: str, reply_to: Optional[str] = None):
#     message = MIMEText(message_text)
#     message["to"] = to
#     message["from"] = sender
#     message["subject"] = subject
#     if reply_to:
#         message["reply-to"] = reply_to
#         message["Cc"] = reply_to 
#     raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
#     return {"raw": raw_message}

# def send_gmail_message(service, user_id: str, message: dict):
#     try:
#         result = service.users().messages().send(userId=user_id, body=message).execute()
#         return result is not None
#     except HttpError:
#         return False

# # ------------------------------------------
# # LLM (OpenAI) Message Generation Helpers
# # ------------------------------------------
# def refine_message_with_feedback(
#     original_message: str,
#     feedback: str,
# ) -> Tuple[str, str]:
#     api_key = os.getenv("OPENAI_API_KEY")
#     llm = ChatOpenAI(
#         model="gpt-4o-mini",
#         temperature=0.7,
#         max_tokens=600,
#         openai_api_key=api_key
#     )
#     prompt = f"""
#     Please refine the following recruitment message based on the provided feedback:

#     ORIGINAL MESSAGE:
#     {original_message}

#     FEEDBACK:
#     {feedback}

#     Please provide your response in the following format:
#     SUBJECT: [Your subject line here]

#     BODY:
#     [Your refined email body content here]
#     Keep the same tone and intent as the original message, but incorporate the feedback to improve it.
#     """
#     try:
#         messages = [
#             SystemMessage(content="You are a professional recruitment message writer. Refine the given message based on feedback while maintaining professionalism and the original intent."),
#             HumanMessage(content=prompt)
#         ]
#         response = llm.invoke(messages)
#         content = response.content.strip()
#         subject_line = ""
#         body_content = ""
#         lines = content.split('\n')
#         body_found = False
#         body_lines = []
#         for line in lines:
#             if line.strip().startswith('SUBJECT:'):
#                 subject_line = line.replace('SUBJECT:', '').strip()
#             elif line.strip().startswith('BODY:'):
#                 body_found = True
#             elif body_found and line.strip():
#                 body_lines.append(line)
#         body_content = '\n'.join(body_lines).strip()
#         if not subject_line:
#             subject_line = "Recruitment Opportunity - Updated"
#         if not body_content:
#             body_content = content
#         return subject_line, body_content
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=f"Error refining message: {str(e)}")

# def generate_recruitment_message_with_subject(
#     msg_type: str,
#     company: str,
#     role_title: str,
#     recruiter: str,
#     org: str,
#     candidate: str,
#     current_pos: str,
#     evaluation: str,
#     feedback: Optional[str] = None
# ) -> Tuple[str, str]:
#     api_key = os.getenv("OPENAI_API_KEY")
#     llm = ChatOpenAI(
#         model="gpt-4o-mini",
#         temperature=0.7,
#         max_tokens=600,
#         openai_api_key=api_key
#     )
#     base_prompt = f"""
#     Generate a professional recruitment {msg_type} with the following details:
#     - Company hiring: {company}
#     - Role: {role_title}
#     - Recruiter: {recruiter} from {org}
#     - Candidate: {candidate}
#     - Candidate's current position: {current_pos}
#     - Evaluation: {evaluation}
#     """
#     if msg_type == "outreach":
#         prompt = base_prompt + """
#         Create an initial outreach message that:
#         - Introduces the recruiter and organization
#         - Mentions the specific role and company
#         - Expresses interest in discussing the opportunity
#         - Keeps it short and to the point.
#         - Do not include any placeholders like [Candidate Name] or [Role Title] in the email.
#         """
#     elif msg_type == "introductory":
#         prompt = base_prompt + """
#         Create an introductory message that:
#         - Thanks the candidate for their initial response
#         - Provides more details about the role and company
#         - Explains why this opportunity aligns with their background
#         - Suggests next steps (like a call or meeting)
#         - Maintains a warm, professional tone
#         """
#     else:  # followup
#         prompt = base_prompt + """
#         Create a follow-up message that:
#         - References previous communication
#         - Reiterates interest in the candidate
#         - Addresses any potential concerns
#         - Provides additional compelling reasons to consider the role
#         - Includes a clear call to action
#         """
#     if feedback:
#         prompt += f"\n\nPlease modify the message based on this feedback: {feedback}"
#     prompt += """

#     Please provide your response in the following format:
#     SUBJECT: [Your subject line here]

#     BODY:
#     [Your email body content here]
#     """
#     try:
#         messages = [
#             SystemMessage(content="You are a professional recruitment message writer. Generate both an email subject line and body content. Follow the exact format requested."),
#             HumanMessage(content=prompt)
#         ]
#         response = llm.invoke(messages)
#         content = response.content.strip()
#         subject_line = ""
#         body_content = ""
#         lines = content.split('\n')
#         body_found = False
#         body_lines = []
#         for line in lines:
#             if line.strip().startswith('SUBJECT:'):
#                 subject_line = line.replace('SUBJECT:', '').strip()
#             elif line.strip().startswith('BODY:'):
#                 body_found = True
#             elif body_found and line.strip():
#                 body_lines.append(line)
#         body_content = '\n'.join(body_lines).strip()
#         if not subject_line:
#             subject_line = f"Opportunity at {company} - {role_title}"
#         if not body_content:
#             body_content = content
#         return subject_line, body_content
#     except Exception as e:
#         raise HTTPException(status_code=500, detail=f"Error generating message: {str(e)}")

# # ------------------------------------------
# # FastAPI Endpoints
# # ------------------------------------------
# @app.get("/")
# async def root():
#     return {
#         "message": "Recruitment Message Generator API",
#         "version": "1.0.0",
#         "endpoints": [
#             "/generate-message",
#             "/refine-message",
#             "/authenticate",
#             "/docs"
#         ]
#     }

# @app.post("/generate-message", response_model=MessageResponse)
# async def generate_message(request: GenerateMessageRequest, background_tasks: BackgroundTasks):
#     try:
#         current_position = f"{request.current_role} at {request.current_company}"
#         email_subject, generated_message = generate_recruitment_message_with_subject(
#             msg_type=request.message_type.value.replace('followup', 'follow-up'),
#             company=request.company_name,
#             role_title=request.role,
#             recruiter=request.recruiter_name,
#             org=request.organisation,
#             candidate=request.candidate_name,
#             current_pos=current_position,
#             evaluation=request.job_evaluation
#         )
#         email_sent = False
#         if request.send_email:
#             registered_users = []
#             if os.path.exists("registered_users.csv"):
#                 df = pd.read_csv("registered_users.csv")
#                 registered_users = df['email'].tolist() if 'email' in df.columns else []
#             if request.sender_email.lower() not in [user.lower() for user in registered_users]:
#                 return MessageResponse(
#                     success=True,
#                     message=generated_message,
#                     email_sent=False,
#                     email_subject=email_subject,
#                     error="Email not sent: Sender email is not registered"
#                 )
#             service = authenticate_gmail(request.sender_email)
#             if service:
#                 email_message = create_email_message(
#                     sender=request.sender_email,
#                     to=request.recipient_email,
#                     subject=email_subject,
#                     message_text=generated_message,
#                     reply_to=request.reply_to_email
#                 )
#                 email_sent = send_gmail_message(service, "me", email_message)
#                 if not email_sent:
#                     return MessageResponse(
#                         success=True,
#                         message=generated_message,
#                         email_sent=False,
#                         email_subject=email_subject,
#                         error="Email not sent: Failed to send via Gmail API"
#                     )
#             else:
#                 return MessageResponse(
#                     success=True,
#                     message=generated_message,
#                     email_sent=False,
#                     email_subject=email_subject,
#                     error="Email not sent: Gmail authentication failed"
#                 )
#         return MessageResponse(
#             success=True,
#             message=generated_message,
#             email_sent=email_sent,
#             email_subject=email_subject
#         )
#     except Exception as e:
#         return MessageResponse(
#             success=False,
#             message="",
#             error=str(e)
#         )

# @app.post("/refine-message", response_model=MessageResponse)
# async def refine_message(request: FeedbackRequest):
#     try:
#         email_subject, refined_message = refine_message_with_feedback(
#             original_message=request.message,
#             feedback=request.feedback
#         )
#         return MessageResponse(
#             success=True,
#             message=refined_message,
#             email_sent=False,
#             email_subject=email_subject
#         )
#     except Exception as e:
#         return MessageResponse(
#             success=False,
#             message="",
#             error=str(e)
#         )

# @app.post("/authenticate", response_model=AuthenticateResponse)
# async def authenticate_user(request: AuthenticateRequest):
#     try:
#         if check_user_token_exists(request.email):
#             service = authenticate_gmail(request.email, create_if_missing=False)
#             if service:
#                 return AuthenticateResponse(
#                     success=True,
#                     message="User already authenticated and token is valid"
#                 )
#             else:
#                 service = authenticate_gmail(request.email, create_if_missing=True)
#                 if service:
#                     return AuthenticateResponse(
#                         success=True,
#                         message="Token refreshed successfully"
#                     )
#                 else:
#                     return AuthenticateResponse(
#                         success=False,
#                         message="Failed to refresh token",
#                         error="Could not refresh existing token. Please check credentials.json"
#                     )
#         else:
#             try:
#                 creds = create_new_credentials(request.email)
#                 if creds:
#                     return AuthenticateResponse(
#                         success=True,
#                         message="Authentication successful. Token created and saved."
#                     )
#                 else:
#                     return AuthenticateResponse(
#                         success=False,
#                         message="Authentication failed",
#                         error="Failed to create credentials"
#                     )
#             except Exception as e:
#                 return AuthenticateResponse(
#                     success=False,
#                     message="Authentication failed",
#                     error=str(e)
#                 )
#     except Exception as e:
#         return AuthenticateResponse(
#             success=False,
#             message="Authentication error",
#             error=str(e)
#         )

# @app.get("/health")
# async def health_check():
#     return {"status": "healthy", "timestamp": datetime.utcnow().isoformat()}

# if __name__ == "__main__":
#     import uvicorn
#     uvicorn.run(app, host="0.0.0.0", port=8000)



from fastapi import FastAPI, HTTPException, BackgroundTasks
from pydantic import BaseModel, EmailStr, Field
from typing import Optional, Tuple
from enum import Enum
import os
import base64
import pickle
import pandas as pd
from dotenv import load_dotenv
from langchain_openai import ChatOpenAI
from langchain.schema import HumanMessage, SystemMessage
from email.mime.text import MIMEText
from google.auth.transport.requests import Request
from google.oauth2.credentials import Credentials
from google_auth_oauthlib.flow import InstalledAppFlow
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from datetime import datetime
import json

# Load environment variables (not needed on Hugging Face, but harmless)
load_dotenv()

# ------------------------------------------
# Helper: Write GOOGLE_CREDENTIALS_JSON to file if needed
# ------------------------------------------
def ensure_credentials_file():
    credentials_env = os.getenv("GOOGLE_CREDENTIALS_JSON")
    credentials_path = "credentials_SYNAPSE.json"
    if not os.path.exists(credentials_path):
        if not credentials_env:
            raise Exception("GOOGLE_CREDENTIALS_JSON not found in environment variables.")
        try:
            parsed_json = json.loads(credentials_env)
        except json.JSONDecodeError:
            raise Exception("Invalid JSON in GOOGLE_CREDENTIALS_JSON")
        with open(credentials_path, "w") as f:
            json.dump(parsed_json, f, indent=2)
    return credentials_path

# ------------------------------------------
# FastAPI app
# ------------------------------------------
app = FastAPI(title="Recruitment Message Generator API", version="1.0.0")

SCOPES = ["https://www.googleapis.com/auth/gmail.send"]
openai_api_key = os.getenv("OPENAI_API_KEY")

# ------------------------------------------
# Enums and Models
# ------------------------------------------
class MessageType(str, Enum):
    OUTREACH = "outreach"
    INTRODUCTORY = "introductory"
    FOLLOWUP = "followup"

class GenerateMessageRequest(BaseModel):
    job_evaluation: str
    sender_email: EmailStr
    reply_to_email: Optional[EmailStr] = Field(None, description="Recruiter's email for reply-to header")
    recipient_email: EmailStr
    candidate_name: str
    current_role: str
    current_company: str
    company_name: str
    role: str
    recruiter_name: str
    organisation: str
    message_type: MessageType
    send_email: bool = False

class FeedbackRequest(BaseModel):
    message: str
    feedback: str

class AuthenticateRequest(BaseModel):
    email: EmailStr

class AuthenticateResponse(BaseModel):
    success: bool
    message: str
    error: Optional[str] = None

class MessageResponse(BaseModel):
    success: bool
    message: str
    email_sent: bool = False
    email_subject: Optional[str] = None
    error: Optional[str] = None

class SendMessageRequest(BaseModel):
    subject: str
    email_body: str
    sender_email: EmailStr
    recipient_email: EmailStr
    reply_to_email: Optional[EmailStr] = None

# ------------------------------------------
# Gmail Helper Functions
# ------------------------------------------
def get_token_file_path(email: str) -> str:
    tokens_dir = "gmail_tokens"
    if not os.path.exists(tokens_dir):
        os.makedirs(tokens_dir)
    safe_email = email.replace("@", "_at_").replace(".", "_dot_")
    return os.path.join(tokens_dir, f"token_{safe_email}.pickle")

def check_user_token_exists(email: str) -> bool:
    token_file = get_token_file_path(email)
    return os.path.exists(token_file)

def load_user_credentials(email: str):
    token_file = get_token_file_path(email)
    if os.path.exists(token_file):
        try:
            with open(token_file, 'rb') as token:
                creds = pickle.load(token)
                return creds
        except Exception:
            if os.path.exists(token_file):
                os.remove(token_file)
    return None

def save_user_credentials(email: str, creds):
    token_file = get_token_file_path(email)
    with open(token_file, 'wb') as token:
        pickle.dump(creds, token)

def create_new_credentials(email: str):
    credentials_path = ensure_credentials_file()
    flow = InstalledAppFlow.from_client_secrets_file(
        credentials_path, SCOPES
    )
    creds = flow.run_local_server(port=0)
    save_user_credentials(email, creds)
    return creds

def authenticate_gmail(email: str, create_if_missing: bool = False):
    creds = load_user_credentials(email)
    if creds:
        if creds.expired and creds.refresh_token:
            try:
                creds.refresh(Request())
                save_user_credentials(email, creds)
            except Exception:
                if create_if_missing:
                    try:
                        creds = create_new_credentials(email)
                    except:
                        return None
                else:
                    return None
        elif not creds.valid:
            creds = None
    if not creds:
        if create_if_missing:
            try:
                creds = create_new_credentials(email)
            except:
                return None
        else:
            return None
    try:
        service = build("gmail", "v1", credentials=creds)
        return service
    except Exception:
        return None

def create_email_message(sender: str, to: str, subject: str, message_text: str, reply_to: Optional[str] = None):
    message = MIMEText(message_text)
    message["to"] = to
    message["from"] = sender
    message["subject"] = subject
    if reply_to:
        message["reply-to"] = reply_to
        message["Cc"] = reply_to 
    raw_message = base64.urlsafe_b64encode(message.as_bytes()).decode()
    return {"raw": raw_message}

def send_gmail_message(service, user_id: str, message: dict):
    try:
        result = service.users().messages().send(userId=user_id, body=message).execute()
        return result is not None
    except HttpError:
        return False

# ------------------------------------------
# LLM (OpenAI) Message Generation Helpers
# ------------------------------------------
def refine_message_with_feedback(
    original_message: str,
    feedback: str,
) -> Tuple[str, str]:
    api_key = os.getenv("OPENAI_API_KEY")
    llm = ChatOpenAI(
        model="gpt-4o-mini",
        temperature=0.7,
        max_tokens=600,
        openai_api_key=api_key
    )
    prompt = f"""
    Please refine the following recruitment message based on the provided feedback:

    ORIGINAL MESSAGE:
    {original_message}

    FEEDBACK:
    {feedback}

    Please provide your response in the following format:
    SUBJECT: [Your subject line here]

    BODY:
    [Your refined email body content here]
    Keep the same tone and intent as the original message, but incorporate the feedback to improve it.
    """
    try:
        messages = [
            SystemMessage(content="You are a professional recruitment message writer. Refine the given message based on feedback while maintaining professionalism and the original intent."),
            HumanMessage(content=prompt)
        ]
        response = llm.invoke(messages)
        content = response.content.strip()
        subject_line = ""
        body_content = ""
        lines = content.split('\n')
        body_found = False
        body_lines = []
        for line in lines:
            if line.strip().startswith('SUBJECT:'):
                subject_line = line.replace('SUBJECT:', '').strip()
            elif line.strip().startswith('BODY:'):
                body_found = True
            elif body_found and line.strip():
                body_lines.append(line)
        body_content = '\n'.join(body_lines).strip()
        if not subject_line:
            subject_line = "Recruitment Opportunity - Updated"
        if not body_content:
            body_content = content
        return subject_line, body_content
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error refining message: {str(e)}")

def generate_recruitment_message_with_subject(
    msg_type: str,
    company: str,
    role_title: str,
    recruiter: str,
    org: str,
    candidate: str,
    current_pos: str,
    evaluation: str,
    feedback: Optional[str] = None
) -> Tuple[str, str]:
    api_key = os.getenv("OPENAI_API_KEY")
    llm = ChatOpenAI(
        model="gpt-4o-mini",
        temperature=0.7,
        max_tokens=600,
        openai_api_key=api_key
    )
    base_prompt = f"""
    Generate a professional recruitment {msg_type} with the following details:
    - Company hiring: {company}
    - Role: {role_title}
    - Recruiter: {recruiter} from {org}
    - Candidate: {candidate}
    - Candidate's current position: {current_pos}
    - Evaluation: {evaluation}
    """
    if msg_type == "outreach":
        prompt = base_prompt + """
        Create an initial outreach message that:
        - Introduces the recruiter and organization
        - Mentions the specific role and company
        - Expresses interest in discussing the opportunity
        - Keeps it short and to the point.
        - Do not include any placeholders like [Candidate Name] or [Role Title] in the email.
        """
    elif msg_type == "introductory":
        prompt = base_prompt + """
        Create an introductory message that:
        - Thanks the candidate for their initial response
        - Provides more details about the role and company
        - Explains why this opportunity aligns with their background
        - Suggests next steps (like a call or meeting)
        - Maintains a warm, professional tone
        """
    else:  # followup
        prompt = base_prompt + """
        Create a follow-up message that:
        - References previous communication
        - Reiterates interest in the candidate
        - Addresses any potential concerns
        - Provides additional compelling reasons to consider the role
        - Includes a clear call to action
        """
    if feedback:
        prompt += f"\n\nPlease modify the message based on this feedback: {feedback}"
    prompt += """

    Please provide your response in the following format:
    SUBJECT: [Your subject line here]

    BODY:
    [Your email body content here]
    """
    try:
        messages = [
            SystemMessage(content="You are a professional recruitment message writer. Generate both an email subject line and body content. Follow the exact format requested."),
            HumanMessage(content=prompt)
        ]
        response = llm.invoke(messages)
        content = response.content.strip()
        subject_line = ""
        body_content = ""
        lines = content.split('\n')
        body_found = False
        body_lines = []
        for line in lines:
            if line.strip().startswith('SUBJECT:'):
                subject_line = line.replace('SUBJECT:', '').strip()
            elif line.strip().startswith('BODY:'):
                body_found = True
            elif body_found and line.strip():
                body_lines.append(line)
        body_content = '\n'.join(body_lines).strip()
        if not subject_line:
            subject_line = f"Opportunity at {company} - {role_title}"
        if not body_content:
            body_content = content
        return subject_line, body_content
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Error generating message: {str(e)}")

# ------------------------------------------
# FastAPI Endpoints
# ------------------------------------------
@app.get("/")
async def root():
    return {
        "message": "Recruitment Message Generator API",
        "version": "1.0.0",
        "endpoints": [
            "/generate-message",
            "/refine-message",
            "/authenticate",
            "/send-message",
            "/docs"
            
        ]
    }

@app.post("/send-message", response_model=MessageResponse)
async def send_message(request: SendMessageRequest):
    try:
        # Authenticate sender
        service = authenticate_gmail(request.sender_email)
        if not service:
            return MessageResponse(
                success=False,
                message="",
                error="Gmail authentication failed"
            )
        # Create the email
        email_message = create_email_message(
            sender=request.sender_email,
            to=request.recipient_email,
            subject=request.subject,
            message_text=request.email_body,
            reply_to=request.reply_to_email
        )
        # Send the email
        email_sent = send_gmail_message(service, "me", email_message)
        if email_sent:
            return MessageResponse(
                success=True,
                message="Email sent successfully.",
                email_sent=True,
                email_subject=request.subject
            )
        else:
            return MessageResponse(
                success=False,
                message="",
                email_sent=False,
                email_subject=request.subject,
                error="Failed to send via Gmail API"
            )
    except Exception as e:
        return MessageResponse(
            success=False,
            message="",
            error=str(e)
        )

@app.post("/generate-message", response_model=MessageResponse)
async def generate_message(request: GenerateMessageRequest, background_tasks: BackgroundTasks):
    try:
        current_position = f"{request.current_role} at {request.current_company}"
        email_subject, generated_message = generate_recruitment_message_with_subject(
            msg_type=request.message_type.value.replace('followup', 'follow-up'),
            company=request.company_name,
            role_title=request.role,
            recruiter=request.recruiter_name,
            org=request.organisation,
            candidate=request.candidate_name,
            current_pos=current_position,
            evaluation=request.job_evaluation
        )
        email_sent = False
        if request.send_email:
            registered_users = []
            if os.path.exists("registered_users.csv"):
                df = pd.read_csv("registered_users.csv")
                registered_users = df['email'].tolist() if 'email' in df.columns else []
            if request.sender_email.lower() not in [user.lower() for user in registered_users]:
                return MessageResponse(
                    success=True,
                    message=generated_message,
                    email_sent=False,
                    email_subject=email_subject,
                    error="Email not sent: Sender email is not registered"
                )
            service = authenticate_gmail(request.sender_email)
            if service:
                email_message = create_email_message(
                    sender=request.sender_email,
                    to=request.recipient_email,
                    subject=email_subject,
                    message_text=generated_message,
                    reply_to=request.reply_to_email
                )
                email_sent = send_gmail_message(service, "me", email_message)
                if not email_sent:
                    return MessageResponse(
                        success=True,
                        message=generated_message,
                        email_sent=False,
                        email_subject=email_subject,
                        error="Email not sent: Failed to send via Gmail API"
                    )
            else:
                return MessageResponse(
                    success=True,
                    message=generated_message,
                    email_sent=False,
                    email_subject=email_subject,
                    error="Email not sent: Gmail authentication failed"
                )
        return MessageResponse(
            success=True,
            message=generated_message,
            email_sent=email_sent,
            email_subject=email_subject
        )
    except Exception as e:
        return MessageResponse(
            success=False,
            message="",
            error=str(e)
        )

@app.post("/refine-message", response_model=MessageResponse)
async def refine_message(request: FeedbackRequest):
    try:
        email_subject, refined_message = refine_message_with_feedback(
            original_message=request.message,
            feedback=request.feedback
        )
        return MessageResponse(
            success=True,
            message=refined_message,
            email_sent=False,
            email_subject=email_subject
        )
    except Exception as e:
        return MessageResponse(
            success=False,
            message="",
            error=str(e)
        )

@app.post("/authenticate", response_model=AuthenticateResponse)
async def authenticate_user(request: AuthenticateRequest):
    try:
        if check_user_token_exists(request.email):
            service = authenticate_gmail(request.email, create_if_missing=False)
            if service:
                return AuthenticateResponse(
                    success=True,
                    message="User already authenticated and token is valid"
                )
            else:
                service = authenticate_gmail(request.email, create_if_missing=True)
                if service:
                    return AuthenticateResponse(
                        success=True,
                        message="Token refreshed successfully"
                    )
                else:
                    return AuthenticateResponse(
                        success=False,
                        message="Failed to refresh token",
                        error="Could not refresh existing token. Please check credentials.json"
                    )
        else:
            try:
                creds = create_new_credentials(request.email)
                if creds:
                    return AuthenticateResponse(
                        success=True,
                        message="Authentication successful. Token created and saved."
                    )
                else:
                    return AuthenticateResponse(
                        success=False,
                        message="Authentication failed",
                        error="Failed to create credentials"
                    )
            except Exception as e:
                return AuthenticateResponse(
                    success=False,
                    message="Authentication failed",
                    error=str(e)
                )
    except Exception as e:
        return AuthenticateResponse(
            success=False,
            message="Authentication error",
            error=str(e)
        )

@app.get("/health")
async def health_check():
    return {"status": "healthy", "timestamp": datetime.utcnow().isoformat()}

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)