File size: 28,587 Bytes
943774e
 
 
 
b17c56b
943774e
 
 
 
6489563
 
943774e
 
 
 
 
 
 
a13b1c9
 
6489563
c0754a0
6489563
 
 
 
 
 
 
 
a13b1c9
 
6489563
 
 
a13b1c9
 
 
 
 
 
 
 
 
 
 
 
 
943774e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6489563
 
 
 
 
 
 
 
 
 
943774e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6489563
 
 
 
 
 
 
 
 
 
 
 
 
943774e
 
6489563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
943774e
6489563
 
 
 
 
 
 
 
943774e
 
6489563
 
943774e
6489563
943774e
6489563
 
943774e
6489563
 
 
 
 
943774e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b17c56b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6489563
 
 
b17c56b
 
 
 
 
 
 
 
 
 
 
 
 
 
943774e
 
 
 
 
6489563
 
 
 
943774e
 
 
6489563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
943774e
 
 
 
 
6489563
 
 
 
 
 
 
943774e
 
6489563
 
 
 
 
943774e
 
 
6489563
943774e
 
 
 
 
 
 
6489563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b887a7
943774e
6489563
 
 
 
943774e
 
6489563
 
 
 
 
 
 
 
943774e
 
6489563
 
 
943774e
 
 
 
 
6489563
943774e
6489563
 
 
 
 
 
 
943774e
6489563
 
943774e
 
 
6489563
 
 
 
 
943774e
6489563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
943774e
6489563
 
 
 
943774e
6489563
 
 
 
 
943774e
 
 
 
 
6489563
 
943774e
6489563
943774e
6489563
 
 
 
943774e
 
 
 
 
 
 
 
 
 
 
 
6489563
 
 
 
 
 
 
 
 
 
 
 
 
943774e
6489563
 
943774e
 
 
 
 
a13b1c9
 
6489563
4b887a7
6489563
4b887a7
a13b1c9
 
6489563
b17c56b
6489563
b17c56b
4b887a7
a13b1c9
943774e
a13b1c9
4b887a7
 
 
a13b1c9
 
 
b17c56b
 
 
4b887a7
a13b1c9
943774e
a13b1c9
6489563
 
 
a13b1c9
 
 
b17c56b
 
 
4b887a7
a13b1c9
943774e
a13b1c9
4b887a7
6489563
 
 
 
 
 
4b887a7
a13b1c9
 
6489563
b17c56b
 
 
4b887a7
a13b1c9
943774e
a13b1c9
943774e
b17c56b
6489563
 
 
 
 
 
a13b1c9
943774e
a13b1c9
6489563
 
 
943774e
6489563
 
 
a13b1c9
6489563
a13b1c9
4b887a7
6489563
 
4b887a7
a13b1c9
6489563
 
 
a13b1c9
6489563
a13b1c9
4b887a7
6489563
 
4b887a7
a13b1c9
 
 
6489563
 
 
a13b1c9
 
4b887a7
6489563
4b887a7
 
6489563
4b887a7
 
 
 
 
6489563
 
 
4b887a7
 
 
 
 
 
 
 
 
6489563
 
 
 
 
 
 
 
 
a13b1c9
4b887a7
6489563
 
4b887a7
a13b1c9
6489563
 
 
a13b1c9
4b887a7
6489563
 
4b887a7
a13b1c9
4b887a7
6489563
 
4b887a7
a13b1c9
4b887a7
6489563
 
4b887a7
a13b1c9
6489563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
a13b1c9
 
4b887a7
6489563
 
4b887a7
a13b1c9
 
 
6489563
 
 
 
 
 
a13b1c9
 
6489563
 
 
 
 
 
 
 
 
a13b1c9
4b887a7
a13b1c9
 
6489563
 
 
 
 
 
4b887a7
 
 
 
 
 
6489563
 
 
 
 
 
 
 
 
 
 
 
 
a13b1c9
 
6489563
 
 
 
a13b1c9
943774e
6489563
a13b1c9
 
b17c56b
a13b1c9
b17c56b
 
 
 
 
 
 
 
 
6489563
b17c56b
a13b1c9
4b887a7
 
6489563
 
 
 
4b887a7
 
 
 
 
6489563
 
 
4b887a7
6489563
 
4b887a7
6489563
 
4b887a7
a13b1c9
 
6489563
b17c56b
a13b1c9
 
 
 
 
 
 
 
943774e
 
6489563
 
 
 
b17c56b
 
 
6489563
 
 
 
 
 
b17c56b
6489563
4b887a7
 
 
 
 
b17c56b
6489563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b17c56b
 
 
 
6489563
 
 
 
b17c56b
 
4b887a7
b17c56b
943774e
a13b1c9
 
6489563
 
 
 
 
b17c56b
 
 
 
 
 
4b887a7
b17c56b
 
 
6489563
 
 
 
b17c56b
 
 
 
6489563
b17c56b
 
 
 
943774e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b17c56b
 
943774e
 
 
 
 
 
6489563
943774e
6489563
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
943774e
 
 
 
 
 
 
 
 
6489563
943774e
 
 
 
 
a13b1c9
6489563
943774e
 
 
 
 
6489563
943774e
 
6489563
 
 
 
943774e
 
 
 
6489563
943774e
 
 
a13b1c9
6489563
943774e
 
 
 
6489563
943774e
 
b17c56b
 
 
 
 
6489563
943774e
 
6489563
 
 
b17c56b
943774e
 
6489563
 
 
 
 
 
 
 
 
 
 
 
 
b17c56b
 
 
 
6489563
 
 
 
 
943774e
 
6489563
943774e
6489563
 
 
 
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
import os
import json
import re
import tempfile
from typing import Dict, Any

import pandas as pd
import gradio as gr
import PyPDF2
from huggingface_hub import InferenceClient


# =========================
# Config
# =========================
APP_TITLE = "Procelevate TalentMatch AI"
APP_SUBTITLE = "Agentic AI for Data Analyst / Data Engineering Candidate Screening"
PROCELEVATE_BLUE = "#0F2C59"
MAX_RESUMES = 5

# Hugging Face configuration
HF_TOKEN = os.getenv("Talent_Search_AI")
HF_MODEL = os.getenv("HF_MODEL", "Qwen/Qwen2.5-7B-Instruct")

hf_client = InferenceClient(
    model=HF_MODEL,
    token=HF_TOKEN,
) if HF_TOKEN else None


DEFAULT_JD = """Role: Data Analyst / Data Engineer

We are looking for candidates with experience in SQL, Python, data visualization,
ETL pipelines, data cleaning, dashboarding, and cloud data platforms.
Exposure to Power BI, Tableau, Azure, AWS, Snowflake, Airflow, or Spark is preferred.

Responsibilities:
- Analyze large datasets and generate insights
- Build and maintain data pipelines
- Create dashboards and business reports
- Work with stakeholders to gather requirements
- Ensure data quality and governance

Preferred:
- 3+ years of experience
- Strong communication skills
- Experience in analytics and engineering environments
"""


# =========================
# Utility Functions
# =========================
def clean_text(text: str) -> str:
    if not text:
        return ""
    return re.sub(r"\s+", " ", text).strip()


def read_pdf(file_path: str) -> str:
    text = ""
    try:
        with open(file_path, "rb") as f:
            reader = PyPDF2.PdfReader(f)
            for page in reader.pages:
                page_text = page.extract_text()
                if page_text:
                    text += page_text + "\n"
    except Exception as e:
        return f"Error reading PDF: {str(e)}"

    text = clean_text(text)

    if not text:
        return (
            "Error reading PDF: No machine-readable text was found. "
            "This PDF may be image-based/scanned."
        )

    return text


def read_txt(file_path: str) -> str:
    try:
        with open(file_path, "r", encoding="utf-8", errors="ignore") as f:
            return clean_text(f.read())
    except Exception as e:
        return f"Error reading TXT: {str(e)}"


def file_to_text(file_obj) -> str:
    if file_obj is None:
        return ""

    file_path = file_obj if isinstance(file_obj, str) else file_obj.name
    lower = file_path.lower()

    if lower.endswith(".pdf"):
        return read_pdf(file_path)
    elif lower.endswith(".txt"):
        return read_txt(file_path)
    else:
        return "Unsupported file format. Please upload PDF or TXT."


def extract_json_object(text: str) -> Dict[str, Any]:
    """
    Robustly extract JSON even if the model wraps it in markdown fences.
    """
    if not text:
        return {"error": "The model returned an empty response."}

    text = text.strip()

    # Remove ```json ... ``` or ``` ... ```
    if text.startswith("```"):
        text = re.sub(r"^```(?:json)?\s*", "", text, flags=re.IGNORECASE)
        text = re.sub(r"\s*```$", "", text)

    try:
        return json.loads(text)
    except Exception:
        pass

    # Fall back to the first top-level-looking JSON object
    match = re.search(r"\{.*\}", text, flags=re.DOTALL)
    if match:
        try:
            return json.loads(match.group(0))
        except Exception as e:
            return {
                "error": f"Model returned text that could not be parsed as JSON: {str(e)}",
                "raw_response": text[:1200],
            }

    return {
        "error": "Model response did not contain a valid JSON object.",
        "raw_response": text[:1200],
    }


def call_llm_json(
    system_prompt: str,
    user_prompt: str,
    max_tokens: int = 1200
) -> Dict[str, Any]:
    """
    Calls a Hugging Face hosted instruction model and returns parsed JSON.
    """
    if not hf_client:
        return {
            "error": (
                "HF_TOKEN is not set. Add your Hugging Face token "
                "to the Space Secrets."
            )
        }

    try:
        response = hf_client.chat_completion(
            messages=[
                {
                    "role": "system",
                    "content": (
                        system_prompt
                        + "\nIMPORTANT: Return exactly one valid JSON object. "
                          "Do not use markdown fences or add commentary."
                    ),
                },
                {"role": "user", "content": user_prompt},
            ],
            max_tokens=max_tokens,
            temperature=0.2,
        )

        content = response.choices[0].message.content
        return extract_json_object(content)

    except Exception as e:
        return {
            "error": (
                f"Hugging Face inference failed using model '{HF_MODEL}': {str(e)}"
            )
        }


def safe_list_to_text(value) -> str:
    if isinstance(value, list):
        return ", ".join(str(v) for v in value)
    if value is None:
        return ""
    return str(value)


def get_decision_band(recommendation: str) -> str:
    rec = (recommendation or "").strip().lower()
    if rec == "shortlist":
        return "Green"
    elif rec == "hold":
        return "Amber"
    elif rec == "reject":
        return "Red"
    return "Review"


def build_candidate_detail(record: Dict[str, Any]) -> str:
    return f"""
### Candidate Detail Review

**Candidate:** {record.get('Candidate', '')}  
**Current Role:** {record.get('Current Role', '')}  
**Experience:** {record.get('Experience (Yrs)', '')} years  
**Location:** {record.get('Location', '')}  
**Role Fit:** {record.get('Role Fit', '')}  
**Match Score:** {record.get('Match Score', '')}  
**Recommendation:** {record.get('Recommendation', '')}  
**Decision Band:** {record.get('Decision Band', '')}

---

**Why Selected**  
{record.get('Why Selected', '')}

**Matched Skills**  
{record.get('Matched Skills', '')}

**Missing Skills / Gaps**  
{record.get('Missing Skills / Gaps', '')}

**Interview Focus Areas**  
{record.get('Interview Focus Areas', '')}

**Recommended HR Action**  
{record.get('Recommended HR Action', '')}

**Outreach Message**  
{record.get('Outreach Message', '')}

**Response Intent**  
{record.get('Response Intent', '')}

**Final Status**  
{record.get('Final Status', '')}

**Next Step**  
{record.get('Next Step', '')}

**Bias-Safe Review Note**  
{record.get('Bias-Safe Review Note', '')}
"""


# =========================
# Agent Functions
# =========================
def resume_intake_agent(resume_text: str) -> Dict[str, Any]:
    system_prompt = """
You are Resume Intake Agent, an HR talent-screening assistant.
Extract only information explicitly supported by the resume.
Do not infer protected or sensitive personal attributes.
If a field is unavailable, use an empty string or empty list.
"""

    user_prompt = f"""
Extract the following candidate information from the resume.

Return JSON with exactly these keys:
{{
  "candidate_name": "",
  "email": "",
  "phone": "",
  "current_location": "",
  "total_experience_years": "",
  "current_role": "",
  "current_company": "",
  "skills": [],
  "tools_technologies": [],
  "education": [],
  "certifications": [],
  "projects_summary": "",
  "relevant_data_analyst_experience": "",
  "relevant_data_engineering_experience": "",
  "likely_notice_period": "",
  "summary": ""
}}

Rules:
- Do not invent experience, skills, employers, notice period, or qualifications.
- If notice period is not explicitly stated, return "".
- Keep lists concise.

Resume Text:
{resume_text}
"""

    return call_llm_json(system_prompt, user_prompt, max_tokens=1400)


def jd_matching_agent(
    jd_text: str,
    candidate_profile: Dict[str, Any]
) -> Dict[str, Any]:

    system_prompt = """
You are JD Matching Agent.
Evaluate a candidate only against job-related requirements.
Use skills, relevant experience, tools, responsibilities, and qualifications.
Do not consider protected or sensitive personal attributes.
Be explainable and conservative.
"""

    user_prompt = f"""
Compare the candidate profile against the Job Description.

Job Description:
{jd_text}

Candidate Profile:
{json.dumps(candidate_profile, indent=2)}

Return JSON:
{{
  "role_fit": "Data Analyst / Data Engineer / Both / Low Fit",
  "match_score": 0,
  "matched_skills": [],
  "missing_skills": [],
  "why_selected": [],
  "interview_focus_areas": [],
  "recommended_hr_action": "",
  "bias_safe_review_note": ""
}}

Scoring guidance:
- 80-100: strong alignment
- 60-79: partial/moderate alignment
- below 60: weak alignment

Important:
- Score only from evidence in the candidate profile and JD.
- Missing information is not evidence of capability.
- Do not invent candidate experience.
- Keep matched/missing skill lists focused on important JD requirements.
"""

    return call_llm_json(system_prompt, user_prompt, max_tokens=1300)


def outreach_agent(
    candidate_name: str,
    role_title: str,
    recommendation: str
) -> Dict[str, Any]:

    system_prompt = """
You are Candidate Outreach Agent.
Create concise, professional recruiter outreach.
Avoid promises about hiring outcomes.
"""

    user_prompt = f"""
Candidate Name: {candidate_name}
Role Title: {role_title}
Screening Recommendation: {recommendation}

Return JSON:
{{
  "whatsapp_message": "",
  "email_message": ""
}}

Keep the messages professional and short.
"""

    return call_llm_json(system_prompt, user_prompt, max_tokens=500)


def response_classifier_agent(candidate_response: str) -> Dict[str, Any]:
    """
    Lightweight rule-based classifier for the simulated demo response.
    This avoids spending an additional LLM inference call on predictable text.
    """
    text = (candidate_response or "").lower().strip()

    if not text:
        intent = "Unclear"
        summary = "No response received."
        next_action = "Follow up later if appropriate."

    elif any(
        phrase in text
        for phrase in [
            "not interested",
            "not looking",
            "no thanks",
            "decline",
        ]
    ):
        intent = "Not Interested"
        summary = "Candidate is currently not interested in pursuing the opportunity."
        next_action = "Close or retain the profile for future relevant opportunities."

    elif any(
        phrase in text
        for phrase in [
            "more details",
            "share details",
            "tell me more",
            "role details",
        ]
    ):
        intent = "Needs More Information"
        summary = "Candidate requested additional information about the opportunity."
        next_action = "Share the role details and answer candidate questions."

    elif any(
        phrase in text
        for phrase in [
            "later",
            "next month",
            "after",
            "currently busy",
        ]
    ):
        intent = "Available Later"
        summary = "Candidate may be open to discussion at a later date."
        next_action = "Schedule an appropriate follow-up."

    elif any(
        phrase in text
        for phrase in [
            "interested",
            "available",
            "discuss",
            "yes",
        ]
    ):
        intent = "Interested"
        summary = "Candidate expressed interest in discussing the opportunity."
        next_action = "Proceed to recruiter screening or interview scheduling."

    else:
        intent = "Unclear"
        summary = "Candidate intent could not be confidently determined."
        next_action = "Request clarification from the candidate."

    return {
        "intent": intent,
        "summary": summary,
        "recommended_next_action": next_action,
    }


def hr_summary_agent(
    candidate_profile: Dict[str, Any],
    match_result: Dict[str, Any],
    response_result: Dict[str, Any],
    recommendation: str,
) -> Dict[str, Any]:

    system_prompt = """
You are HR Summary Agent.
Prepare a concise recruiter-ready briefing for human review.
Do not make the final hiring decision.
Use only supplied evidence.
"""

    user_prompt = f"""
Candidate Profile:
{json.dumps(candidate_profile, indent=2)}

JD Match Result:
{json.dumps(match_result, indent=2)}

Candidate Response Result:
{json.dumps(response_result, indent=2)}

System Recommendation:
{recommendation}

Return JSON:
{{
  "final_status": "",
  "recruiter_summary": "",
  "interview_readiness": "",
  "recommended_next_step": "",
  "recruiter_action_pack": []
}}

The final_status should describe workflow status, not a final employment decision.
"""

    return call_llm_json(system_prompt, user_prompt, max_tokens=800)


# =========================
# Main Workflow
# =========================
def run_talentmatch(role_title: str, jd_text: str, resume_files):
    try:
        if not HF_TOKEN:
            error_df = pd.DataFrame(
                [{"Error": "HF_TOKEN is not set in Hugging Face Space Secrets."}]
            )
            return (
                error_df,
                "HF_TOKEN is not set.",
                gr.Dropdown(choices=[], value=None),
                "Please configure HF_TOKEN in Hugging Face Space Secrets.",
                None,
                {},
            )

        if not jd_text or not jd_text.strip():
            error_df = pd.DataFrame(
                [{"Error": "Please paste or keep the default Job Description."}]
            )
            return (
                error_df,
                "Please paste or keep the default Job Description.",
                gr.Dropdown(choices=[], value=None),
                "Please provide a Job Description.",
                None,
                {},
            )

        if not resume_files:
            error_df = pd.DataFrame(
                [{"Error": "Please upload at least one resume."}]
            )
            return (
                error_df,
                "Please upload at least one resume.",
                gr.Dropdown(choices=[], value=None),
                "Please upload at least one resume.",
                None,
                {},
            )

        if len(resume_files) > MAX_RESUMES:
            error_df = pd.DataFrame(
                [{
                    "Error": (
                        f"Please upload maximum {MAX_RESUMES} resumes per run "
                        "for optimal performance."
                    )
                }]
            )
            return (
                error_df,
                f"Please upload maximum {MAX_RESUMES} resumes per run.",
                gr.Dropdown(choices=[], value=None),
                f"Reduce the uploaded resumes to {MAX_RESUMES} or fewer.",
                None,
                {},
            )

        records = []

        for file_obj in resume_files:
            file_name = (
                file_obj
                if isinstance(file_obj, str)
                else getattr(file_obj, "name", "resume")
            )

            resume_text = file_to_text(file_obj)

            if resume_text.startswith("Error"):
                raise Exception(
                    f"Resume read failed for {file_name}: {resume_text}"
                )

            # -----------------------------
            # Agent 1: Resume Intake
            # -----------------------------
            candidate_profile = resume_intake_agent(resume_text)

            if "error" in candidate_profile:
                raise Exception(
                    f"Resume Intake Agent failed for {file_name}: "
                    f"{candidate_profile['error']}"
                )

            # -----------------------------
            # Agent 2: JD Matching
            # -----------------------------
            match_result = jd_matching_agent(jd_text, candidate_profile)

            if "error" in match_result:
                raise Exception(
                    f"JD Matching Agent failed for {file_name}: "
                    f"{match_result['error']}"
                )

            candidate_name = (
                candidate_profile.get("candidate_name")
                or os.path.basename(file_name)
                .replace(".pdf", "")
                .replace(".txt", "")
            )

            # -----------------------------
            # Deterministic Decision Engine
            # -----------------------------
            raw_score = match_result.get("match_score", 0)

            try:
                score = float(raw_score)
            except Exception:
                score = 0.0

            # Keep score in valid range
            score = max(0.0, min(100.0, score))

            if score >= 80:
                recommendation = "Shortlist"
            elif score >= 60:
                recommendation = "Hold"
            else:
                recommendation = "Reject"

            match_result["recommendation"] = recommendation

            # -----------------------------
            # Agent 3: Outreach
            # -----------------------------
            outreach = outreach_agent(
                candidate_name,
                role_title,
                recommendation,
            )

            if "error" in outreach:
                raise Exception(
                    f"Outreach Agent failed for {file_name}: "
                    f"{outreach['error']}"
                )

            # -----------------------------
            # Demo Candidate Response
            # -----------------------------
            if recommendation == "Shortlist":
                simulated_response = (
                    "Yes, I am interested and available to discuss "
                    "this opportunity further."
                )
            elif recommendation == "Hold":
                simulated_response = (
                    "Please share more details about the role, "
                    "team structure, and work location."
                )
            else:
                simulated_response = (
                    "Thank you for reaching out. "
                    "I am currently not looking for a change."
                )

            # -----------------------------
            # Agent 4: Response Classifier
            # Rule-based for demo efficiency
            # -----------------------------
            response_result = response_classifier_agent(
                simulated_response
            )

            # -----------------------------
            # Agent 5: HR Summary
            # -----------------------------
            hr_summary = hr_summary_agent(
                candidate_profile,
                match_result,
                response_result,
                recommendation,
            )

            if "error" in hr_summary:
                raise Exception(
                    f"HR Summary Agent failed for {file_name}: "
                    f"{hr_summary['error']}"
                )

            decision_band = get_decision_band(recommendation)

            outreach_message = (
                outreach.get("whatsapp_message")
                or outreach.get("email_message")
                or ""
            )

            record = {
                "Candidate": candidate_name,
                "Current Role": candidate_profile.get(
                    "current_role", ""
                ),
                "Experience (Yrs)": candidate_profile.get(
                    "total_experience_years", ""
                ),
                "Location": candidate_profile.get(
                    "current_location", ""
                ),
                "Role Fit": match_result.get("role_fit", ""),
                "Match Score": score,
                "Recommendation": recommendation,
                "Decision Band": decision_band,
                "Why Selected": safe_list_to_text(
                    match_result.get("why_selected", [])
                ),
                "Matched Skills": safe_list_to_text(
                    match_result.get("matched_skills", [])
                ),
                "Missing Skills / Gaps": safe_list_to_text(
                    match_result.get("missing_skills", [])
                ),
                "Interview Focus Areas": safe_list_to_text(
                    match_result.get("interview_focus_areas", [])
                ),
                "Recommended HR Action": match_result.get(
                    "recommended_hr_action", ""
                ),
                "Outreach Message": outreach_message,
                "Response Intent": response_result.get(
                    "intent", ""
                ),
                "Final Status": hr_summary.get(
                    "final_status", ""
                ),
                "Next Step": hr_summary.get(
                    "recommended_next_step", ""
                ),
                "Bias-Safe Review Note": match_result.get(
                    "bias_safe_review_note",
                    (
                        "Recommendation is based on job-related "
                        "skills, experience, tools, and role fit only."
                    ),
                ),
            }

            records.append(record)

        full_df = pd.DataFrame(records)

        compact_columns = [
            "Candidate",
            "Current Role",
            "Experience (Yrs)",
            "Role Fit",
            "Match Score",
            "Recommendation",
            "Decision Band",
        ]

        compact_df = full_df[compact_columns].copy()

        avg_score = (
            round(
                pd.to_numeric(
                    full_df["Match Score"],
                    errors="coerce",
                ).fillna(0).mean(),
                1,
            )
            if len(full_df)
            else 0
        )

        shortlisted = int(
            (full_df["Recommendation"] == "Shortlist").sum()
        )
        hold_count = int(
            (full_df["Recommendation"] == "Hold").sum()
        )
        reject_count = int(
            (full_df["Recommendation"] == "Reject").sum()
        )

        summary_text = (
            f"Model: {HF_MODEL}\n"
            f"Total Candidates: {len(full_df)}\n"
            f"Shortlisted: {shortlisted}\n"
            f"Hold: {hold_count}\n"
            f"Rejected: {reject_count}\n"
            f"Average Match Score: {avg_score}\n\n"
            f"Decision Band Logic:\n"
            f"- Green = Shortlist\n"
            f"- Amber = Hold\n"
            f"- Red = Reject"
        )

        csv_path = os.path.join(
            tempfile.gettempdir(),
            "talentmatch_screening_results.csv",
        )
        full_df.to_csv(csv_path, index=False)

        candidate_choices = full_df["Candidate"].tolist()
        default_candidate = (
            candidate_choices[0]
            if candidate_choices
            else None
        )

        first_record = records[0] if records else {}

        detail_markdown = (
            build_candidate_detail(first_record)
            if first_record
            else "No candidate details available."
        )

        # Duplicate candidate names could collide, so make keys unique.
        state_data = {}
        unique_choices = []

        for idx, record in enumerate(records, start=1):
            base_name = record["Candidate"] or f"Candidate {idx}"
            display_name = base_name

            if display_name in state_data:
                display_name = f"{base_name} ({idx})"

            state_data[display_name] = record
            unique_choices.append(display_name)

        default_candidate = (
            unique_choices[0]
            if unique_choices
            else None
        )

        return (
            compact_df,
            summary_text,
            gr.Dropdown(
                choices=unique_choices,
                value=default_candidate,
            ),
            detail_markdown,
            csv_path,
            state_data,
        )

    except Exception as e:
        error_message = f"Workflow failed: {str(e)}"

        error_df = pd.DataFrame(
            [{"Error": error_message}]
        )

        return (
            error_df,
            error_message,
            gr.Dropdown(choices=[], value=None),
            error_message,
            None,
            {},
        )


def update_candidate_detail(
    selected_candidate,
    state_data,
):
    if not selected_candidate or not state_data:
        return "No candidate selected."

    record = state_data.get(selected_candidate)

    if not record:
        return "Candidate details not found."

    return build_candidate_detail(record)


# =========================
# UI Styling
# =========================
custom_css = f"""
body {{
    background: white;
}}

h1, h2, h3 {{
    color: {PROCELEVATE_BLUE} !important;
}}

.gradio-container {{
    max-width: 1320px !important;
}}

.procelevate-header {{
    text-align: center;
    margin-bottom: 10px;
}}

.notice-box {{
    border: 1px solid #d9e2f0;
    background: #f8fbff;
    border-radius: 12px;
    padding: 14px;
    margin-top: 8px;
    margin-bottom: 16px;
}}
"""


# =========================
# Gradio App
# =========================
with gr.Blocks(css=custom_css, title=APP_TITLE) as demo:
    state_store = gr.State({})

    gr.HTML(
        f"""
        <div class="procelevate-header">
            <h1>{APP_TITLE}</h1>
            <h3>{APP_SUBTITLE}</h3>
        </div>

        <div class="notice-box">
            <b>Prototype Scope:</b>
            This demo shows how Agentic AI can support HR teams by parsing resumes,
            matching profiles to a job description, generating shortlist recommendations,
            drafting outreach, interpreting candidate responses, and preparing recruiter-ready summaries.
            <br><br>

            <b>AI Provider:</b>
            Hugging Face hosted inference using <b>{HF_MODEL}</b>.
            <br><br>

            <b>Enterprise Upgrade:</b>
            This version adds explainability, interview focus guidance,
            decision bands, HR action recommendations, and a bias-safe review note.
            <br><br>

            <b>Important:</b>
            This is a decision-support system. Final hiring decisions remain with HR.
            <br><br>

            <b>Usage Note:</b>
            Upload up to {MAX_RESUMES} resumes per run for stable demo performance.
        </div>
        """
    )

    with gr.Row():
        with gr.Column(scale=2):
            role_title = gr.Textbox(
                label="Role Title",
                value="Data Analyst / Data Engineer",
                placeholder="Enter target role",
            )

            jd_text = gr.Textbox(
                label="Paste Job Description",
                lines=14,
                value=DEFAULT_JD,
                placeholder="Paste the JD here...",
            )

            resume_files = gr.File(
                label="Upload Candidate Resumes (PDF or TXT)",
                file_count="multiple",
                file_types=[".pdf", ".txt"],
            )

            run_button = gr.Button(
                "Run TalentMatch Workflow",
                variant="primary",
            )

        with gr.Column(scale=1):
            output_summary = gr.Textbox(
                label="Screening Summary",
                lines=12,
            )

            output_file = gr.File(
                label="Download Screening Results CSV",
                visible=True,
            )

    output_df = gr.Dataframe(
        label="Candidate Screening Dashboard",
        interactive=False,
    )

    gr.Markdown("### Candidate Review Detail")

    candidate_selector = gr.Dropdown(
        label="Select Candidate",
        choices=[],
        value=None,
    )

    candidate_detail = gr.Markdown(
        "Run the workflow to view candidate details."
    )

    run_button.click(
        fn=run_talentmatch,
        inputs=[
            role_title,
            jd_text,
            resume_files,
        ],
        outputs=[
            output_df,
            output_summary,
            candidate_selector,
            candidate_detail,
            output_file,
            state_store,
        ],
    )

    candidate_selector.change(
        fn=update_candidate_detail,
        inputs=[
            candidate_selector,
            state_store,
        ],
        outputs=[candidate_detail],
    )


if __name__ == "__main__":
    demo.launch(
        server_name="0.0.0.0",
        server_port=7860,
    )