Spaces:
Running on Zero

File size: 45,069 Bytes
bf8c887
 
2cdd95e
bf8c887
2cdd95e
bf8c887
2cdd95e
 
 
 
426b73a
bf8c887
2cdd95e
bf8c887
 
345d040
1ddb437
bf8c887
1ddb437
bf8c887
 
 
 
 
 
 
 
 
 
bbd741f
ca82a2f
 
1ddb437
134744e
345d040
 
 
 
 
 
 
 
 
 
 
 
 
 
bf8c887
 
 
 
2cdd95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf8c887
 
 
 
 
bbd741f
ca82a2f
 
 
 
 
 
426b73a
 
 
 
2cdd95e
 
426b73a
 
 
 
 
 
 
 
 
 
 
 
ca82a2f
426b73a
 
 
 
 
 
2cdd95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bf8c887
c71cee1
 
 
 
 
 
 
 
 
bf8c887
b089ad7
 
 
2cdd95e
 
b089ad7
 
 
 
2cdd95e
 
 
 
 
b089ad7
2cdd95e
 
 
 
 
bf8c887
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299e081
 
 
 
 
bf8c887
299e081
 
 
 
bf8c887
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7f2d2d6
 
 
 
 
 
 
 
 
 
 
 
 
 
bf8c887
 
 
 
 
 
 
299e081
bf8c887
 
299e081
bf8c887
 
299e081
 
 
 
ca82a2f
 
299e081
 
 
 
bbd741f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
299e081
a67bd16
 
 
 
 
 
299e081
 
 
 
 
bbd741f
299e081
bbd741f
299e081
a67bd16
 
 
 
299e081
 
 
134744e
299e081
 
 
 
 
a67bd16
 
 
299e081
 
134744e
 
 
 
299e081
 
134744e
 
 
 
 
 
299e081
134744e
 
 
 
 
 
 
 
 
 
 
 
 
299e081
 
bf8c887
 
 
 
299e081
 
 
 
 
 
 
 
 
 
 
 
 
345d040
1ddb437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4b49f26
 
 
 
 
1ddb437
 
4b49f26
 
 
1ddb437
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345d040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2cdd95e
 
345d040
 
 
 
2cdd95e
 
 
 
 
 
 
 
345d040
2cdd95e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
345d040
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
ca82a2f
 
2cdd95e
ca82a2f
 
 
 
2cdd95e
 
 
 
 
ca82a2f
2cdd95e
 
 
 
 
 
 
ca82a2f
 
 
 
 
2cdd95e
 
 
 
 
ca82a2f
 
2cdd95e
ca82a2f
 
 
 
 
 
 
 
 
 
 
2cdd95e
ca82a2f
 
2cdd95e
 
 
 
ca82a2f
2cdd95e
 
 
 
ca82a2f
 
 
 
2cdd95e
 
 
 
 
ca82a2f
 
 
 
2cdd95e
ca82a2f
 
 
 
 
 
bf8c887
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5744cb8
 
 
 
 
 
bf8c887
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import os
import sys
import io
import json
import hmac
import logging
import collections
import time
import zipfile
import threading
from contextlib import asynccontextmanager
from pathlib import Path
from typing import List, Dict, Any, Optional, Tuple

import uvicorn
from fastapi import FastAPI, UploadFile, File, Form, Request, HTTPException, Query
from pydantic import BaseModel
from app.services.embedding_service import EmbeddingUnavailableError
from fastapi.responses import JSONResponse, FileResponse, HTMLResponse
from fastapi.staticfiles import StaticFiles
from fastapi.middleware.cors import CORSMiddleware

# Ensure ATS module importable
ROOT_DIR = Path(__file__).resolve().parent.parent
if str(ROOT_DIR) not in sys.path:
    sys.path.insert(0, str(ROOT_DIR))

from app.adapters.screening_adapter import ATSScreeningAdapter
from app.services.resume_parser import ResumeParserService
from app.services.structured_extractor import StructuredResumeExtractor
from app.services.extraction_service import ExtractionService
from app.adapters.extraction_adapter import ExtractionAdapter
from app.services.mcp_client import mcp_client_service
from app.storage.supabase_client import is_supabase_configured, get_missing_supabase_env_vars
from app.storage.resume_storage import store_resume, ResumePersistenceError, StorageError
from app.storage.candidate_repository import (
    list_candidates,
    search_candidates,
    get_candidate,
    get_resume_download_url,
    delete_candidate,
    CandidateNotFoundError,
    RepositoryUnavailableError,
    PartialDeletionError,
    DatabaseError,
    DEFAULT_PAGE_SIZE,
    MAX_PAGE_SIZE,
)

logger = logging.getLogger("ats_server")
logging.basicConfig(level=logging.INFO)

# ---------------------------------------------------------------------------
# Security & Rate Limiting Constants
# ---------------------------------------------------------------------------
MAX_UPLOAD_SIZE_BYTES = int(os.getenv("MAX_UPLOAD_SIZE_BYTES", str(5 * 1024 * 1024)))  # 5 MB
MAX_PAGE_COUNT = int(os.getenv("MAX_PAGE_COUNT", "15"))  # 15 pages
MAX_DOCX_UNCOMPRESSED_BYTES = int(os.getenv("MAX_DOCX_UNCOMPRESSED_BYTES", str(20 * 1024 * 1024)))  # 20 MB

# Global safety-net caps; per-user rate limiting is the Node layer's job.
RATE_LIMIT_GLOBAL_EXTRACT_MAX = int(os.getenv("RATE_LIMIT_GLOBAL_EXTRACT_MAX", "120"))  # 120 / min
RATE_LIMIT_GLOBAL_JOBS_MAX = int(os.getenv("RATE_LIMIT_GLOBAL_JOBS_MAX", "600"))  # 600 / min

_INTERNAL_SECRET_ENV = "ATS_INTERNAL_SECRET"


def is_production_mode() -> bool:
    """Detects whether server is running in production mode."""
    env = os.getenv("ENVIRONMENT", "").lower()
    is_prod_flag = os.getenv("PRODUCTION", "").lower() in ("true", "1")
    is_hf_space = bool(os.getenv("SPACE_ID"))
    return env in ("production", "prod") or is_prod_flag or is_hf_space


_rate_limit_records: Dict[str, list] = collections.defaultdict(list)
_rate_limit_lock = threading.Lock()


def check_rate_limit(key: str, max_requests: int, window_seconds: int = 60) -> bool:
    """Global sliding-window rate limiter with timestamp eviction. Thread-safe."""
    now = time.time()
    with _rate_limit_lock:
        timestamps = _rate_limit_records[key]
        # Evict stale entries
        _rate_limit_records[key] = [t for t in timestamps if now - t < window_seconds]
        if len(_rate_limit_records[key]) >= max_requests:
            return False
        _rate_limit_records[key].append(now)
        return True


def verify_internal_secret(request: Request) -> None:
    """
    Validates the X-ATS-Internal-Secret header using constant-time compare.
    - In production mode, rejects with 401 if ATS_INTERNAL_SECRET is unset.
    - If ATS_INTERNAL_SECRET is configured, requires matching header.
    - In non-production mode with unset secret, allows request for local dev/testing.
    Raises HTTPException(401) on failure.
    """
    configured = os.environ.get(_INTERNAL_SECRET_ENV, "").strip()
    if not configured:
        if is_production_mode():
            raise HTTPException(
                status_code=401,
                detail={
                    "error": "Internal secret not configured. Set ATS_INTERNAL_SECRET on the HF Space.",
                    "header": "X-ATS-Internal-Secret",
                },
            )
        return  # skip in non-production when secret is unset

    provided = request.headers.get("X-ATS-Internal-Secret", "")
    if not hmac.compare_digest(provided, configured):
        raise HTTPException(
            status_code=401,
            detail={"error": "Invalid or missing X-ATS-Internal-Secret header."},
        )


def check_lfs_assets_status() -> Tuple[bool, Dict[str, int]]:
    """Checks file sizes of required ML/DB assets to distinguish real binaries from LFS text pointers."""
    asset_files = [
        ROOT_DIR / "data" / "ats_metadata.db",
        ROOT_DIR / "data" / "bm25_index.pkl",
        ROOT_DIR / "data" / "xgb_ranker.joblib",
    ]
    sizes = {}
    all_ok = True
    for f in asset_files:
        if f.exists():
            sz = os.path.getsize(f)
            sizes[f.name] = sz
            if sz <= 1000:  # LFS text pointer is ~130 bytes
                all_ok = False
        else:
            sizes[f.name] = 0
            all_ok = False
    return all_ok, sizes


def validate_uploaded_file(content: bytes, filename: str) -> None:
    """Enforces size limits, extension matching, magic bytes, and page caps."""
    if len(content) > MAX_UPLOAD_SIZE_BYTES:
        raise HTTPException(
            status_code=413,
            detail=f"File exceeds maximum allowed size ({MAX_UPLOAD_SIZE_BYTES // (1024 * 1024)}MB).",
        )

    ext = Path(filename).suffix.lower()
    if ext == ".pdf":
        if not content.startswith(b"%PDF-"):
            raise HTTPException(status_code=400, detail="Corrupted or invalid PDF magic bytes.")
        try:
            import fitz
            doc = fitz.open(stream=content, filetype="pdf")
            if doc.page_count > MAX_PAGE_COUNT:
                raise HTTPException(
                    status_code=400,
                    detail=f"PDF exceeds maximum allowed length of {MAX_PAGE_COUNT} pages (received {doc.page_count}).",
                )
        except HTTPException:
            raise
        except Exception as e:
            raise HTTPException(status_code=400, detail=f"Unreadable PDF document: {e}")
    elif ext == ".docx":
        if not content.startswith(b"PK\x03\x04"):
            raise HTTPException(status_code=400, detail="Corrupted or invalid DOCX magic bytes.")
        try:
            with zipfile.ZipFile(io.BytesIO(content)) as zf:
                # 1. Must contain word/document.xml — otherwise it's not a valid DOCX
                member_names = {info.filename for info in zf.infolist()}
                if "word/document.xml" not in member_names:
                    raise HTTPException(
                        status_code=400,
                        detail="Invalid DOCX file: missing word/document.xml (not a Word document).",
                    )
                # 2. Cap total uncompressed size to guard against zip-bomb
                total_uncompressed = sum(info.file_size for info in zf.infolist())
                if total_uncompressed > MAX_DOCX_UNCOMPRESSED_BYTES:
                    raise HTTPException(
                        status_code=400,
                        detail=(
                            f"DOCX uncompressed content exceeds maximum allowed size "
                            f"({MAX_DOCX_UNCOMPRESSED_BYTES // (1024 * 1024)}MB)."
                        ),
                    )
        except HTTPException:
            raise
        except zipfile.BadZipFile:
            raise HTTPException(status_code=400, detail="Corrupted DOCX file: could not open as ZIP archive.")
        except Exception as exc:
            raise HTTPException(status_code=400, detail=f"Unreadable DOCX document: {exc}")
    elif ext == ".txt":
        try:
            decoded = content.decode("utf-8")
            if "\x00" in decoded:
                raise HTTPException(status_code=400, detail="Invalid text file: binary NUL byte detected.")
        except UnicodeDecodeError:
            raise HTTPException(status_code=400, detail="Invalid text file: cannot decode as UTF-8.")
    else:
        raise HTTPException(status_code=400, detail="Unsupported file format. Please upload PDF, DOCX, or TXT.")


# Reference client build path
REF_CLIENT_DIST = Path(r"C:\Users\LENOVO\Downloads\Resume Screening and Shortlisting agent\Resume Screening and Shortlisting agent\e2e-chatbot-app-next\client\dist")

adapter = ATSScreeningAdapter()
parser = ResumeParserService()
structured_extractor = StructuredResumeExtractor(nlp_extractor=adapter.nlp_extractor)
extraction_service = ExtractionService(fallback_extractor=structured_extractor)
extraction_adapter = ExtractionAdapter(
    extraction_service=extraction_service,
    legacy_extractor=structured_extractor,
)

@asynccontextmanager
async def lifespan(app: FastAPI):
    """Lifespan context manager for FastAPI startup and shutdown."""
    logger.info("[Server] Lifespan startup: Starting ExtractionService...")
    assets_ok, asset_sizes = check_lfs_assets_status()
    logger.info("[Server] LFS assets verification on boot: assets_ok=%s, sizes=%s", assets_ok, asset_sizes)
    try:
        await extraction_service.start()
        logger.info("[Server] ExtractionService started successfully.")
    except Exception as exc:
        logger.error("[Server] ExtractionService failed to start during lifespan startup: %s", exc, exc_info=True)
    yield
    logger.info("[Server] Lifespan shutdown: Stopping ExtractionService...")
    try:
        await extraction_service.stop()
        logger.info("[Server] ExtractionService stopped successfully.")
    except Exception as exc:
        logger.error("[Server] ExtractionService failed to stop during lifespan shutdown: %s", exc, exc_info=True)

app = FastAPI(
    title="Hybrid Semantic ATS - Reference UI Server",
    version="1.0.0",
    lifespan=lifespan,
)

# Enable CORS restricted to configured origins
allowed_origins_env = os.getenv("ALLOWED_ORIGINS")
if allowed_origins_env:
    origins = [o.strip() for o in allowed_origins_env.split(",") if o.strip()]
    app.add_middleware(
        CORSMiddleware,
        allow_origins=origins,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )
else:
    origin_regex = os.getenv(
        "ALLOWED_ORIGIN_REGEX",
        r"^https?://(localhost|127\.0\.0\.1)(:\d+)?$|^https://.*\.onrender\.com$|^https://.*\.hf\.space$",
    )
    app.add_middleware(
        CORSMiddleware,
        allow_origin_regex=origin_regex,
        allow_credentials=True,
        allow_methods=["*"],
        allow_headers=["*"],
    )

@app.get("/")
def root():
    return {
        "status": "healthy",
        "service": "Hybrid Semantic ATS Engine",
        "docs": "/docs",
        "health": "/health"
    }

@app.get("/health")
async def health():
    if not extraction_service.running or not extraction_service.is_model_loaded:
        await extraction_service.ensure_worker()
    assets_ok, _ = check_lfs_assets_status()
    rss_mb = extraction_service.get_current_rss_mb()
    is_loading = (
        extraction_service.model_loader_task is not None
        and not extraction_service.model_loader_task.done()
    )
    return {
        "status": "healthy",
        "service": "Hybrid Semantic ATS",
        "assets_ok": assets_ok,
        "model_loaded": extraction_service.is_model_loaded,
        "model_loading": is_loading,
        "shadow_enabled": extraction_service.is_shadow_mode_active,
        "queue_depth": extraction_service.queue_depth,
        "rss_mb": round(rss_mb, 2),
        "cutover_percentage": extraction_service.current_cutover_percentage,
    }

@app.get("/api/session")
async def get_session(request: Request):
    """
    Session endpoint required by SessionContext.tsx.
    Detects Databricks auth headers when running on Databricks Apps,
    or returns an authenticated local reviewer session for browser access.
    """
    user_email = (
        request.headers.get("X-Forwarded-Email")
        or request.headers.get("X-Forwarded-User")
        or request.headers.get("X-Forwarded-Preferred-Username")
        or "reviewer@ats-workspace.local"
    )
    user_name = (
        request.headers.get("X-Forwarded-Preferred-Username")
        or request.headers.get("X-Forwarded-User")
        or "ATS Reviewer"
    )
    return {
        "user": {
            "email": user_email,
            "name": user_name,
            "preferredUsername": user_name,
        }
    }

@app.get("/api/config")
async def get_config():
    """
    Configuration endpoint required by AppConfigContext.tsx.
    """
    return {
        "features": {
            "chatHistory": False,
            "feedback": False,
        },
        "greeting": "Hybrid Semantic ATS Candidate Screening",
    }

def process_resume_upload(
    filename: str,
    content: bytes,
    content_type: str = "application/pdf"
) -> Dict[str, Any] | JSONResponse:
    """
    Core resume ingestion logic:
    1. Parses resume text from PDF, DOCX, or TXT.
    2. If Supabase is configured, extracts structured candidate details and persists
       both original file and metadata with SHA-256 duplicate detection.
    """
    suffix = Path(filename).suffix.lower()
    if suffix not in (".pdf", ".docx", ".txt"):
        return JSONResponse(
            status_code=400,
            content={"error": "Please upload a PDF, DOCX, or TXT resume."}
        )

    # Save to temp location
    temp_dir = ROOT_DIR / "data" / "temp_uploads"
    temp_dir.mkdir(parents=True, exist_ok=True)
    temp_path = temp_dir / filename

    with open(temp_path, "wb") as f:
        f.write(content)

    try:
        ok, raw_text, cleaned_text, file_hash, err = parser.parse_file(temp_path)
        if not ok or not (cleaned_text or raw_text):
            # Check if content is already pre-extracted text (e.g. from MCP read_file tool)
            try:
                decoded = content.decode("utf-8", errors="ignore")
                if decoded and len(decoded.strip()) > 20:
                    import ftfy
                    from app.utils.text_cleaner import clean_text
                    raw_text = ftfy.fix_text(decoded)
                    cleaned_text = clean_text(raw_text)
                    file_hash = hashlib.sha256(content).hexdigest()
                    ok = True
            except Exception:
                pass

        if not ok or not (cleaned_text or raw_text):
            return JSONResponse(
                status_code=400,
                content={"error": err or "The resume was uploaded, but no readable text could be extracted."}
            )

        text_to_return = cleaned_text or raw_text
        response_payload = {
            "success": True,
            "pathname": filename,
            "contentType": content_type,
            "resumeText": text_to_return
        }

        # Persistent storage integration
        if is_supabase_configured():
            try:
                # Structured extraction using the feature-flagged adapter (SLM if enabled, with safe fallback)
                extracted = extraction_adapter.extract(
                    raw_text=raw_text or cleaned_text,
                    cleaned_text=cleaned_text or raw_text
                )

                candidate_name = extracted.get("candidateName") or "Unknown"
                candidate_role = extracted.get("jobTitle") or "Role not identified"
                email = extracted.get("email")  # strictly valid email or None (no em-dashes or blank strings)
                skills = extracted.get("skills")

                # Fallback to deterministic NLP skills if empty
                if not skills:
                    parsed_cand = adapter.nlp_extractor.extract_structured(
                        candidate_id="temp_upload",
                        source_file=filename,
                        file_hash=file_hash,
                        raw_text=raw_text or cleaned_text,
                        cleaned_text=cleaned_text or raw_text
                    )
                    skills = parsed_cand.skills

                current_ver = (
                    extraction_service.current_extractor_version
                    if extraction_service
                    else "ats-slm:qwen2.5-1.5b-instruct:chatml-v1:schema-v1"
                )

                storage_res = store_resume(
                    file_bytes=content,
                    filename=filename,
                    file_hash=file_hash,
                    candidate_name=candidate_name,
                    email=email,
                    resume_text=text_to_return,
                    skills=skills or [],
                    job_role=candidate_role,
                    content_type=content_type or "application/pdf",
                    extracted_data=extracted,
                    extractor_version=current_ver,
                    extraction_source=extracted.get("extractionSource", "legacy"),
                )

                response_payload.update({
                    "persistenceStatus": storage_res.get("persistenceStatus", "persisted"),
                    "candidateId": storage_res.get("candidateId"),
                    "isDuplicate": storage_res.get("isDuplicate", False),
                    "storageObjectPath": storage_res.get("storageObjectPath"),
                    "candidateName": storage_res.get("candidateName"),
                    "jobRole": storage_res.get("jobRole"),
                    "extractedData": extracted,
                    "extractorVersion": current_ver,
                    "extractionSource": extracted.get("extractionSource", "legacy"),
                })
            except Exception as store_err:
                logger.error(
                    f"[Storage] Failed to persist resume '{filename}' (hash: {file_hash[:12]}...): {store_err}",
                    exc_info=True,
                )
                return JSONResponse(
                    status_code=500,
                    content={
                        "success": False,
                        "error": f"Failed to persist resume in Supabase: {str(store_err)}",
                        "persistenceStatus": "failed",
                        "pathname": filename,
                    }
                )
        else:
            missing_vars = get_missing_supabase_env_vars()
            logger.warning(
                "[Storage] Supabase persistent storage is not configured (missing: %s). Operating in temporary in-memory mode.",
                ", ".join(missing_vars) if missing_vars else "unknown",
            )
            response_payload.update({
                "persistenceStatus": "temporary_in_memory",
                "candidateId": None,
                "isDuplicate": False,
                "storageObjectPath": None,
                "persistenceNotice": f"Resume processed in temporary in-memory mode. Missing configuration: {', '.join(missing_vars)}.",
            })

        return response_payload
    finally:
        if temp_path.exists():
            temp_path.unlink()


@app.post("/api/files/upload")
async def upload_resume_file(file: UploadFile = File(...)):
    """
    Implements the exact /api/files/upload endpoint expected by NewChatPage.tsx.
    Extracts text from PDF, DOCX, and TXT using our layout-aware ATS ResumeParserService.
    If Supabase is configured, persists the resume file in Supabase Storage and candidate
    metadata in Supabase Postgres with SHA-256 duplicate detection.
    """
    filename = file.filename or "uploaded_resume.pdf"
    content = await file.read()
    return process_resume_upload(filename, content, file.content_type or "application/pdf")


# =============================================================================
# SharePoint / Microsoft 365 MCP Ingestion Routes
# =============================================================================

class SharePointImportPayload(BaseModel):
    paths: List[str]


class SharePointFetchPayload(BaseModel):
    sharePointLink: str


@app.get("/api/sharepoint/status")
async def sharepoint_status():
    """Returns current MCP connection status and mode (mock vs live)."""
    provider = mcp_client_service.get_provider()
    identity = await provider.whoami()
    return {
        "status": "ok",
        "mock_mode": mcp_client_service.is_mock_mode,
        "mcp_url": getattr(provider, "mcp_url", "https://mcp-resource.onrender.com/mcp"),
        "identity": identity,
    }


@app.get("/api/sharepoint/folders")
async def sharepoint_folders(path: str = Query("", description="Folder path in SharePoint")):
    """
    Lists files and subfolders from SharePoint via MCP provider.
    Supports directory navigation, parent path backtracking, and item metadata.
    """
    provider = mcp_client_service.get_provider()
    try:
        folder_res = await provider.list_folder(path)
        return folder_res.to_dict()
    except Exception as exc:
        logger.error(f"[SharePoint] Failed to list folder '{path}': {exc}")
        raise HTTPException(status_code=500, detail=f"Failed to list SharePoint folder: {exc}")


@app.post("/api/sharepoint/import")
async def sharepoint_import(payload: SharePointImportPayload):
    """
    Imports a batch of selected resume files from SharePoint via MCP provider.
    Streams each file's binary content directly into ResumeParserService and Supabase.
    """
    if not payload.paths:
        raise HTTPException(status_code=400, detail="No file paths provided for import.")

    provider = mcp_client_service.get_provider()
    results = []
    successful = 0
    failed = 0

    for item_path in payload.paths:
        try:
            filename, content, mime_type = await provider.get_file_content(item_path)
            res = process_resume_upload(filename, content, mime_type)

            if isinstance(res, JSONResponse):
                body = json.loads(res.body.decode("utf-8")) if hasattr(res, "body") else {}
                failed += 1
                results.append({
                    "path": item_path,
                    "filename": filename,
                    "success": False,
                    "error": body.get("error", "Failed to parse resume."),
                })
            else:
                successful += 1
                results.append({
                    "path": item_path,
                    "filename": filename,
                    "success": True,
                    "candidateId": res.get("candidateId"),
                    "candidateName": res.get("candidateName"),
                    "jobRole": res.get("jobRole"),
                    "resumeText": res.get("resumeText"),
                    "isDuplicate": res.get("isDuplicate", False),
                    "persistenceStatus": res.get("persistenceStatus", "persisted"),
                    "storageObjectPath": res.get("storageObjectPath"),
                })
        except Exception as exc:
            logger.error(f"[SharePoint] Failed importing file {item_path}: {exc}")
            failed += 1
            results.append({
                "path": item_path,
                "filename": Path(item_path).name,
                "success": False,
                "error": str(exc),
            })

    return {
        "total": len(payload.paths),
        "successful": successful,
        "failed": failed,
        "items": results,
    }


@app.post("/api/sharepoint/fetch-resumes")
async def sharepoint_fetch_resumes(payload: SharePointFetchPayload):
    """
    Backwards-compatible endpoint for existing SharePoint folder link input in NewChatPage.
    Scans the targeted folder, fetches all resumes, and returns structured resume objects.
    """
    provider = mcp_client_service.get_provider()
    raw_link = payload.sharePointLink.strip()

    # Extract target folder path if specified in link
    target_path = ""
    # Check for Canada / Repository role folders in link
    from app.services.mcp_client import CANADA_REPOSITORY_ROLES
    for role in CANADA_REPOSITORY_ROLES:
        if role.lower() in raw_link.lower():
            target_path = f"Repository/{role}"
            break

    if not target_path and "repository" in raw_link.lower():
        target_path = "Repository/AI Engineer"

    try:
        folder_res = await provider.list_folder(target_path)
        file_items = [
            it for it in folder_res.items
            if it.item_type == "file" and it.extension in (".pdf", ".docx", ".txt", "")
        ]

        resumes = []
        for it in file_items:
            try:
                fn, content, mime = await provider.get_file_content(it.path)
                res = process_resume_upload(fn, content, mime)
                if not isinstance(res, JSONResponse):
                    resumes.append({
                        "fileName": fn,
                        "resumeText": res.get("resumeText", ""),
                        "candidateId": res.get("candidateId"),
                        "candidateName": res.get("candidateName"),
                        "jobRole": res.get("jobRole"),
                    })
            except Exception as item_err:
                logger.warning(f"[SharePoint] Skipping file {it.path}: {item_err}")

        return {"resumes": resumes, "count": len(resumes)}
    except Exception as exc:
        logger.error(f"[SharePoint] Error fetching resumes from {raw_link}: {exc}")
        raise HTTPException(status_code=500, detail=str(exc))


@app.get("/api/mcp/callback")
async def mcp_oauth_callback(code: Optional[str] = None, state: Optional[str] = None, error: Optional[str] = None):
    """
    OAuth redirect callback endpoint for Microsoft sign-in via Resource MCP.
    """
    if error:
        return HTMLResponse(
            f"<html><body style='font-family:sans-serif;padding:40px;text-align:center;'>"
            f"<h2 style='color:#b91c1c;'>Microsoft Authentication Failed</h2>"
            f"<p>{error}</p>"
            f"</body></html>",
            status_code=400,
        )

    return HTMLResponse(
        "<html><body style='font-family:sans-serif;padding:40px;text-align:center;background:#f8fafc;'>"
        "<div style='max-width:480px;margin:auto;padding:30px;background:#fff;border-radius:12px;box-shadow:0 4px 12px rgba(0,0,0,0.08);'>"
        "<h2 style='color:#033c67;'>Authentication Successful!</h2>"
        "<p style='color:#64748b;font-size:14px;'>Your session with the Resource MCP has been verified.</p>"
        "<p style='color:#033c67;font-weight:600;'>You may now close this tab and return to the ATS application.</p>"
        "</div>"
        "<script>"
        "if (window.opener) {"
        "  window.opener.postMessage({ type: 'MCP_AUTH_SUCCESS', code: '" + (code or "") + "' }, '*');"
        "}"
        "</script>"
        "</body></html>"
    )


# =============================================================================
# Batch 2: Candidate Repository API
# =============================================================================

def _supabase_required():
    """Return 503 JSON if Supabase is not configured."""
    if not is_supabase_configured():
        missing = get_missing_supabase_env_vars()
        raise HTTPException(
            status_code=503,
            detail={
                "error": "Candidate repository is unavailable: Supabase not configured.",
                "missingConfig": missing,
            },
        )


def _require_delete_auth(request: Request) -> None:
    """
    Guard for destructive (DELETE) endpoints.

    Checks the `Authorization: Bearer <token>` header against the
    `ATS_ADMIN_TOKEN` environment variable on the backend.

    Security model:
      - ATS_ADMIN_TOKEN must be set as a secret env var on the HF Space backend.
      - The Render Node.js proxy should forward the token in an
        `Authorization: Bearer` header when calling DELETE /api/candidates/{id}.
      - If ATS_ADMIN_TOKEN is not set, the endpoint is disabled (503) to prevent
        unauthenticated destructive access in any deployment.
      - CORS and the Supabase service-role key are NOT used as user auth.
      - This token protects the Python backend's direct URL; the Node.js
        frontend's own authMiddleware provides a separate layer on the proxy side.

    Frontend configuration required (Render env or Node proxy):
      Forward the header:  Authorization: Bearer <ATS_ADMIN_TOKEN value>
      Env var name on HF Space: ATS_ADMIN_TOKEN
    """
    configured_token = os.environ.get("ATS_ADMIN_TOKEN", "").strip()
    if not configured_token:
        raise HTTPException(
            status_code=503,
            detail={
                "error": "Destructive operations are disabled: ATS_ADMIN_TOKEN is not configured on this deployment.",
                "action": "Set ATS_ADMIN_TOKEN as a secret environment variable on the backend to enable candidate deletion.",
            },
        )

    auth_header = request.headers.get("Authorization", "")
    if not auth_header.startswith("Bearer "):
        raise HTTPException(
            status_code=401,
            detail={"error": "Authorization header with Bearer token is required for this operation."},
        )

    provided_token = auth_header[len("Bearer "):]
    # Constant-time comparison to prevent timing attacks
    import hmac
    if not hmac.compare_digest(provided_token, configured_token):
        raise HTTPException(
            status_code=403,
            detail={"error": "Invalid admin token."},
        )


@app.get("/api/candidates")
async def list_candidates_endpoint(
    limit: int = Query(default=DEFAULT_PAGE_SIZE, ge=1, le=MAX_PAGE_SIZE),
    offset: int = Query(default=0, ge=0),
):
    """
    List stored candidates with pagination, sorted by newest first.
    Does not return full resume text or internal credentials.
    """
    _supabase_required()
    try:
        result = list_candidates(limit=limit, offset=offset)
        return result
    except RepositoryUnavailableError as exc:
        raise HTTPException(status_code=503, detail=str(exc))
    except DatabaseError as exc:
        logger.error("[API] list_candidates error: %s", exc)
        raise HTTPException(status_code=500, detail="Failed to retrieve candidates.")


@app.get("/api/candidates/search")
async def search_candidates_endpoint(
    q: str = Query(default="", description="Search query (name, email, skills, job role)"),
    limit: int = Query(default=DEFAULT_PAGE_SIZE, ge=1, le=MAX_PAGE_SIZE),
    offset: int = Query(default=0, ge=0),
):
    """
    Case-insensitive search across candidateName, email, jobRole, and skills.
    Returns paginated results. Empty query returns all candidates (same as list).
    """
    _supabase_required()
    try:
        result = search_candidates(query=q, limit=limit, offset=offset)
        return result
    except RepositoryUnavailableError as exc:
        raise HTTPException(status_code=503, detail=str(exc))
    except DatabaseError as exc:
        logger.error("[API] search_candidates error (q=%r): %s", q, exc)
        raise HTTPException(status_code=500, detail="Search failed.")


@app.get("/api/candidates/{candidate_id}")
async def get_candidate_endpoint(
    candidate_id: str,
    include_resume_text: bool = Query(default=False),
):
    """
    Retrieve a single candidate's metadata by UUID.
    Set include_resume_text=true to also return the full extracted resume text.
    """
    _supabase_required()
    try:
        candidate = get_candidate(candidate_id, include_resume_text=include_resume_text)
        return candidate
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))
    except CandidateNotFoundError:
        raise HTTPException(status_code=404, detail=f"Candidate '{candidate_id}' not found.")
    except RepositoryUnavailableError as exc:
        raise HTTPException(status_code=503, detail=str(exc))
    except DatabaseError as exc:
        logger.error("[API] get_candidate(%s) error: %s", candidate_id, exc)
        raise HTTPException(status_code=500, detail="Failed to retrieve candidate.")


@app.get("/api/candidates/{candidate_id}/download")
async def get_candidate_download_url_endpoint(candidate_id: str):
    """
    Generate a short-lived signed URL (5 min TTL) for the candidate's resume file.
    The service-role key is never exposed; permanent public links are not issued.
    """
    _supabase_required()
    try:
        url = get_resume_download_url(candidate_id)
        return {"signedUrl": url, "expiresInSeconds": 300}
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))
    except CandidateNotFoundError:
        raise HTTPException(status_code=404, detail=f"Candidate '{candidate_id}' not found.")
    except RepositoryUnavailableError as exc:
        raise HTTPException(status_code=503, detail=str(exc))
    except Exception as exc:
        logger.error("[API] get_candidate_download_url(%s) error: %s", candidate_id, exc)
        raise HTTPException(status_code=500, detail="Failed to generate download URL.")


@app.delete("/api/candidates/{candidate_id}")
async def delete_candidate_endpoint(candidate_id: str, request: Request):
    """
    Delete a candidate's storage file and metadata record.

    Authorization: requires `Authorization: Bearer <ATS_ADMIN_TOKEN>` header.
    ATS_ADMIN_TOKEN must be set as a secret env var on the HF Space backend.

    Deletion order:
      1. Storage object is deleted first.
         - If Storage deletion fails, returns 409 with the error; the DB row is
           untouched and the operation is safe to retry.
         - If the Storage object is already absent, deletion proceeds normally.
      2. DB row is deleted after Storage succeeds.
         - If DB deletion fails after Storage was removed, returns 207 (partial
           failure) with enough detail to identify and clean up the orphaned row.
      3. ExtractionJobs rows for this candidate's fileHash are cleaned up.
         - Failures here are non-fatal and logged; the main deletion result is returned.
    """
    _require_delete_auth(request)
    _supabase_required()
    try:
        # First, resolve fileHash before deleting — needed for cascade cleanup
        file_hash: Optional[str] = None
        try:
            candidate_detail = get_candidate(candidate_id, include_resume_text=False)
            file_hash = candidate_detail.get("fileHash")
        except Exception:
            pass  # Non-fatal; we still attempt deletion

        result = delete_candidate(candidate_id)

        # Cascade: delete ExtractionJobs rows and clear extractedData for the same fileHash
        if file_hash and is_supabase_configured():
            from app.storage.supabase_client import get_supabase_client
            from app.storage.resume_storage import _get_table_ref as _storage_table_ref

            try:
                from app.storage.candidate_repository import _get_table_ref as _repo_table_ref
                client = get_supabase_client()
                if client:
                    # Delete all ExtractionJobs for this fileHash
                    _repo_table_ref(client, "ExtractionJobs").delete().eq("fileHash", file_hash).execute()
                    logger.info("[API] Deleted ExtractionJobs for fileHash %s (candidate %s)", file_hash[:12], candidate_id)

                    # Clear extractedData + extractorVersion on CandidateResume (may be absent after delete)
                    # Swallow 404-equivalent; the row was just deleted
                    _repo_table_ref(client, "CandidateResume").update({
                        "extractedData": None,
                        "extractorVersion": None,
                    }).eq("fileHash", file_hash).execute()
            except Exception as cascade_err:
                logger.warning(
                    "[API] Cascade cleanup failed for fileHash %s (candidate %s): %s",
                    file_hash[:12] if file_hash else "?", candidate_id, cascade_err,
                )

        return result
    except ValueError as exc:
        raise HTTPException(status_code=400, detail=str(exc))
    except CandidateNotFoundError:
        raise HTTPException(status_code=404, detail=f"Candidate '{candidate_id}' not found.")
    except RepositoryUnavailableError as exc:
        raise HTTPException(status_code=503, detail=str(exc))
    except PartialDeletionError as exc:
        # Storage was deleted but DB row could not be removed.
        # Return 207 Multi-Status so the caller knows the state precisely.
        logger.error("[API] Partial deletion for candidate %s: %s", candidate_id, exc)
        return JSONResponse(
            status_code=207,
            content={
                "deleted": False,
                "partialFailure": True,
                "candidateId": candidate_id,
                "storageDeleted": True,
                "storageAlreadyAbsent": False,
                "dbRowDeleted": False,
                "storageObjectPath": exc.storage_object_path,
                "error": (
                    "Storage file was deleted but the database row could not be removed. "
                    "Retry the DELETE request; the storage step will be skipped automatically."
                ),
            },
        )
    except StorageError as exc:
        # Storage deletion failed — DB row is intact, operation is safe to retry.
        logger.error("[API] Storage deletion failed for candidate %s: %s", candidate_id, exc)
        raise HTTPException(
            status_code=409,
            detail={
                "error": "Could not delete the resume file from storage. The candidate record is intact and the operation is safe to retry.",
                "detail": str(exc),
            },
        )
    except DatabaseError as exc:
        logger.error("[API] delete_candidate(%s) DB error: %s", candidate_id, exc)
        raise HTTPException(status_code=500, detail="Failed to delete candidate record.")


@app.post("/extract")
async def extract_resume_endpoint(
    request: Request,
    file: UploadFile = File(...),
):
    """
    Submits a resume file for async structured extraction:
    - Requires X-ATS-Internal-Secret header (set via env var on HF Space)
    - Enforces global rate limiting (env-configurable, default 120 req/min)
    - Validates file size cap (5MB) and magic bytes (PDF, DOCX, TXT) and page cap (15 pages)
    - Returns 200 (cache hit with full extracted schema) or 202 (queued/deduplicated) or 429 (queue full/rate limit)
    - Never exposes internal storageObjectPath
    """
    # 1. Internal secret authentication (Node proxy must forward X-ATS-Internal-Secret)
    verify_internal_secret(request)

    # 2. Global Rate Limiting (safety net; per-user limiting is Node layer's job)
    if not check_rate_limit("global:extract", max_requests=RATE_LIMIT_GLOBAL_EXTRACT_MAX, window_seconds=60):
        raise HTTPException(status_code=429, detail="Rate limit exceeded for resume upload. Please slow down.")

    try:
        content = await file.read()
        if not content:
            raise HTTPException(status_code=400, detail="Uploaded file is empty.")

        filename = file.filename or "uploaded_resume.pdf"

        # 3. File Validation (magic bytes, size, page cap, DOCX zip-bomb)
        validate_uploaded_file(content, filename)

        status_code, response_data = await extraction_service.submit_job(
            file_bytes=content,
            filename=filename,
            content_type=file.content_type or "application/pdf",
        )
        return JSONResponse(status_code=status_code, content=response_data)
    except HTTPException:
        raise
    except Exception as exc:
        logger.error("[API] /extract error: %s", exc, exc_info=True)
        raise HTTPException(status_code=500, detail=f"Failed to submit extraction job: {str(exc)}")


@app.get("/jobs/{job_id}")
async def get_job_status_endpoint(job_id: str, request: Request):
    """
    Polls the status of an asynchronous resume extraction job.
    - Requires X-ATS-Internal-Secret header
    - Enforces global rate limiting (default 600 req/min)
    - Returns: status ('pending', 'processing', 'completed', 'failed') and result payload when complete.
    - Never exposes internal storageObjectPath
    """
    verify_internal_secret(request)
    if not check_rate_limit("global:jobs", max_requests=RATE_LIMIT_GLOBAL_JOBS_MAX, window_seconds=60):
        raise HTTPException(status_code=429, detail="Rate limit exceeded for job polling. Please slow down.")

    job = extraction_service.get_job(job_id)
    if not job:
        raise HTTPException(status_code=404, detail="Job not found.")

    res_payload = job.get("result")
    if res_payload and isinstance(res_payload, dict):
        res_payload = dict(res_payload)
        res_payload.pop("storageObjectPath", None)

    return {
        "job_id": job["id"],
        "status": job["status"],
        "extractionSource": job.get("extractionSource"),
        "result": res_payload,
        "error": job.get("error"),
        "created_at": job.get("created_at"),
        "updated_at": job.get("updated_at"),
    }


@app.post("/invocations")
async def invocations_endpoint(request: Request):
    """
    Implements MLflow's ResponsesAgent / OpenAI Responses API /invocations endpoint.
    Consumes requests from NewChatPage.tsx (callAgent) and executes the deterministic ATS.
    """
    body = await request.json()
    messages = body.get("input", [])

    if not messages:
        return JSONResponse(
            status_code=400,
            content={"error": "Empty input messages in request."}
        )

    # Get last user prompt
    user_prompt = ""
    for msg in reversed(messages):
        if msg.get("role") == "user":
            content = msg.get("content")
            if isinstance(content, str):
                user_prompt = content
                break
            elif isinstance(content, list):
                parts = [p.get("text", "") for p in content if isinstance(p, dict)]
                user_prompt = " ".join(parts).strip()
                break

    if not user_prompt:
        user_prompt = str(messages[-1])

    # Check if this is an interview question generation request
    if "interview questions" in user_prompt.lower():
        parsed_input = adapter.parse_screening_prompt(user_prompt)
        result_dict = adapter.generate_interview_questions(
            job_title=parsed_input["job_title"],
            job_description=parsed_input["job_description"],
            resume_text=parsed_input["resume_text"]
        )
        final_text = json.dumps(result_dict)
    else:
        # Standard candidate screening request
        parsed_input = adapter.parse_screening_prompt(user_prompt)
        try:
            result_dict = adapter.evaluate_candidate(
                job_title=parsed_input["job_title"],
                job_description=parsed_input["job_description"],
                resume_text=parsed_input["resume_text"]
            )
        except EmbeddingUnavailableError as e:
            # explicit failure instead of a fabricated semantic score (set ALLOW_DEGRADED_SEMANTIC=true to opt in)
            raise HTTPException(status_code=503, detail=str(e))
        final_text = json.dumps(result_dict)

    # Return standard MLflow ResponsesAgent response format
    return {
        "output": [
            {
                "type": "message",
                "role": "assistant",
                "content": [
                    {
                        "type": "output_text",
                        "text": final_text
                    }
                ]
            }
        ],
        "output_text": final_text,
        "text": final_text
    }

# Mount static files from reference client build if available
try:
    client_dist_exists = REF_CLIENT_DIST.exists()
except Exception:
    client_dist_exists = False

if client_dist_exists:
    app.mount("/assets", StaticFiles(directory=str(REF_CLIENT_DIST / "assets")), name="assets")

    @app.get("/{full_path:path}")
    async def serve_spa(full_path: str):
        target = REF_CLIENT_DIST / full_path
        no_cache_headers = {
            "Cache-Control": "no-cache, no-store, must-revalidate",
            "Pragma": "no-cache",
            "Expires": "0"
        }
        if target.is_file():
            return FileResponse(target, headers=no_cache_headers)
        index_file = REF_CLIENT_DIST / "index.html"
        if index_file.exists():
            return FileResponse(index_file, headers=no_cache_headers)
        raise HTTPException(status_code=404, detail="File not found")

def main():
    port = int(os.environ.get("PORT", "8000"))
    uvicorn.run("app.server:app", host="0.0.0.0", port=port, reload=False)

if __name__ == "__main__":
    main()