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
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
import uuid
import json
import logging
from typing import Optional

from fastapi import APIRouter, HTTPException, BackgroundTasks, Query

from app.services import storage, explainer
from app.pipeline.matcher import run_matching
from app.pipeline.skill_parser import parse_skills_string, upgrade_levels_from_work_exp
from app.models.domain import (
    CandidateData, WorkExperience, JDRequirements, SkillRequirement
)
from app.models.schemas import (
    MatchTriggerRequest, MatchTriggerResponse,
    MatchResultsResponse, CandidateMatchResponse, CandidateDetailResponse,
    ScoreBreakdownResponse, SkillMatchInfo, StatusResponse,
)

router = APIRouter(prefix="/api/v1/match", tags=["match"])


# NOTE: /status/{match_id} MUST be declared before /{jd_id} to avoid route
# shadowing β€” FastAPI matches routes in declaration order.
logger = logging.getLogger(__name__)


# ─── Deserializers ────────────────────────────────────────────────────────────

def _dict_to_candidate(d: dict) -> CandidateData:
    work_exps = [
        WorkExperience(
            company=we.get("company", ""),
            role=we.get("role", ""),
            duration=we.get("duration", ""),
            description=we.get("description", ""),
        )
        for we in d.get("work_experiences", [])
    ]
    c = CandidateData(
        id=d["id"],
        name=d["name"],
        current_position=d.get("current_position", ""),
        current_title=d.get("current_title"),
        years_of_experience=float(d.get("years_of_experience", -1)),
        engineer_type=d.get("engineer_type", "Unknown"),
        gen_ai_experience=d.get("gen_ai_experience"),
        parsed_skills=d.get("parsed_skills", ""),
        parsed_summary=d.get("parsed_summary", ""),
        parsed_work_experience_raw=d.get("parsed_work_experience_raw", ""),
        parsed_work_experience_text=d.get("parsed_work_experience_text", ""),
        work_experiences=work_exps,
        extracted_skills=[],
        most_recent_company=d.get("most_recent_company"),
        notice_period=d.get("notice_period"),
        is_actively_looking=d.get("is_actively_looking"),
        flags=list(d.get("flags", [])),
        penalties=list(d.get("penalties", [])),
    )
    return c


def _dict_to_jd(d: dict) -> JDRequirements:
    def parse_skills(raw, is_req) -> list[SkillRequirement]:
        if isinstance(raw, str):
            try:
                raw = json.loads(raw)
            except Exception:
                return []
        result = []
        for s in raw:
            if isinstance(s, dict):
                result.append(SkillRequirement(
                    name=s.get("name", ""),
                    level=int(s.get("level", 3)),
                    is_required=is_req,
                    raw=s.get("raw", ""),
                ))
        return result

    req = parse_skills(d.get("required_skills", "[]"), True)
    pref = parse_skills(d.get("preferred_skills", "[]"), False)
    resp = d.get("responsibilities", [])
    if isinstance(resp, str):
        try:
            resp = json.loads(resp)
        except Exception:
            resp = []

    return JDRequirements(
        id=d.get("jd_id", ""),
        title=d.get("title", ""),
        engineer_type=d.get("engineer_type") or None,
        min_years=float(d.get("min_years", 0)),
        required_skills=req,
        preferred_skills=pref,
        responsibilities=resp,
        raw_text=d.get("full_text", "")[:200],
        full_text=d.get("full_text", ""),
    )


def _result_to_response(r) -> CandidateMatchResponse:
    bd = r.score_breakdown
    return CandidateMatchResponse(
        rank=r.rank,
        candidate_id=r.candidate_id,
        name=r.candidate_name,
        current_position=r.current_position,
        years_of_experience=r.years_of_experience,
        engineer_type=r.engineer_type,
        final_score=round(r.final_score, 4),
        tier=r.tier.value,
        score_breakdown=ScoreBreakdownResponse(
            skill_score=bd.skill_score,
            semantic_score=bd.semantic_score,
            position_score=bd.position_score,
            special_score=bd.special_score,
            final_score=bd.final_score,
            penalties=bd.penalties_applied,
        ),
        matched_skills=[
            SkillMatchInfo(
                skill=s.skill,
                candidate_level=s.candidate_level,
                required_level=s.required_level,
                score=s.score,
                status=s.status,
            )
            for s in bd.matched_skills
        ],
        below_level_skills=[
            SkillMatchInfo(
                skill=s.skill,
                candidate_level=s.candidate_level,
                required_level=s.required_level,
                score=s.score,
                status=s.status,
            )
            for s in bd.below_level_skills
        ],
        missing_skills=bd.missing_skills,
        flags=r.flags,
        notice_period=r.notice_period,
        most_recent_company=r.most_recent_company,
    )


def _result_to_storage_dict(r, candidate: CandidateData) -> dict:
    """Dict for detail hash β€” includes context needed for explanation."""
    bd = r.score_breakdown
    return {
        "candidate_id": r.candidate_id,
        "candidate_name": r.candidate_name,
        "current_position": r.current_position,
        "years_of_experience": r.years_of_experience,
        "engineer_type": r.engineer_type,
        "final_score": r.final_score,
        "tier": r.tier.value,
        "rank": r.rank,
        "flags": json.dumps(r.flags),
        "notice_period": r.notice_period or "",
        "most_recent_company": r.most_recent_company or "",
        "score_breakdown": json.dumps({
            "skill_score": bd.skill_score,
            "semantic_score": bd.semantic_score,
            "position_score": bd.position_score,
            "special_score": bd.special_score,
            "final_score": bd.final_score,
            "penalties": bd.penalties_applied,
            "matched_skills": [
                {"skill": s.skill, "candidate_level": s.candidate_level,
                 "required_level": s.required_level, "score": s.score, "status": s.status}
                for s in bd.matched_skills
            ],
            "below_level_skills": [
                {"skill": s.skill, "candidate_level": s.candidate_level,
                 "required_level": s.required_level, "score": s.score, "status": s.status}
                for s in bd.below_level_skills
            ],
            "missing_skills": bd.missing_skills,
        }),
        # Context for LLM explanation (truncated)
        "parsed_skills": candidate.parsed_skills[:500],
        "parsed_summary": candidate.parsed_summary[:300],
        "parsed_work_experience_text": candidate.parsed_work_experience_text[:600],
    }


# ─── Match background task ────────────────────────────────────────────────────

def _run_match_task(
    match_id: str,
    jd_id: str,
    batch_id: str,
    top_n: int,
):
    """Runs in background. Updates match status in Redis."""
    try:
        storage.set_match_status(match_id, "processing", progress=0.1)

        jd_data = storage.get_jd(jd_id)
        if not jd_data:
            storage.set_match_status(match_id, "failed", message=f"JD {jd_id} not found")
            return

        candidates_json = storage.get_batch_candidates_json(batch_id)
        if not candidates_json:
            storage.set_match_status(match_id, "failed", message=f"Batch {batch_id} not found")
            return

        jd = _dict_to_jd(jd_data)
        raw_candidates = json.loads(candidates_json)
        candidates = [_dict_to_candidate(d) for d in raw_candidates]

        storage.set_match_status(match_id, "processing", progress=0.3)

        results = run_matching(jd, candidates, top_n=top_n)

        storage.set_match_status(match_id, "processing", progress=0.9)

        # Save to Redis
        storage_dicts = []
        cand_map = {c.id: c for c in candidates}
        for r in results:
            cand = cand_map.get(r.candidate_id)
            if cand:
                storage_dicts.append(_result_to_storage_dict(r, cand))

        storage.save_match_results(jd_id, batch_id, storage_dicts)
        storage.set_active_batch(jd_id, batch_id)
        storage.set_match_status(match_id, "completed", progress=1.0)

        logger.info(f"Match {match_id} completed: {len(results)} results")

    except Exception as e:
        logger.exception(f"Match {match_id} failed")
        storage.set_match_status(match_id, "failed", message=str(e))


# ─── Endpoints ────────────────────────────────────────────────────────────────

@router.post("/{jd_id}", response_model=MatchTriggerResponse)
async def trigger_match(
    jd_id: str,
    body: MatchTriggerRequest,
    background_tasks: BackgroundTasks,
):
    jd_data = storage.get_jd(jd_id)
    if not jd_data:
        raise HTTPException(404, f"JD {jd_id} not found")

    batch_meta = storage.get_batch_metadata(body.batch_id)
    if not batch_meta:
        raise HTTPException(404, f"Batch {body.batch_id} not found")

    total = int(batch_meta.get("total_count", 0))
    match_id = f"{jd_id}_{body.batch_id}"
    top_n = body.top_n

    storage.set_match_status(match_id, "pending")
    background_tasks.add_task(_run_match_task, match_id, jd_id, body.batch_id, top_n)

    return MatchTriggerResponse(
        match_id=match_id,
        status="pending",
        total_candidates=total,
        filtered_candidates=total,
    )


@router.get("/{jd_id}", response_model=MatchResultsResponse)
def get_match_results(
    jd_id: str,
    batch_id: Optional[str] = Query(default=None),
    top_n: int = Query(default=10, ge=1, le=50),
):
    if not batch_id:
        batch_id = storage.get_active_batch(jd_id)
    if not batch_id:
        raise HTTPException(404, "No match results yet. Run POST /match/{jd_id} first.")

    jd_data = storage.get_jd(jd_id)
    if not jd_data:
        raise HTTPException(404, f"JD {jd_id} not found")

    ranked = storage.get_ranked_candidates(jd_id, batch_id, top_n)
    if not ranked:
        raise HTTPException(404, "No results found. Match may still be processing.")

    candidates_out: list[CandidateMatchResponse] = []
    for rank_i, (cid, score) in enumerate(ranked, start=1):
        detail = storage.get_candidate_detail(jd_id, batch_id, cid)
        if not detail:
            continue

        bd_raw = detail.get("score_breakdown", "{}")
        if isinstance(bd_raw, str):
            try:
                bd_raw = json.loads(bd_raw)
            except Exception:
                bd_raw = {}

        flags = detail.get("flags", [])
        if isinstance(flags, str):
            try:
                flags = json.loads(flags)
            except Exception:
                flags = []

        def _parse_skill_list(raw):
            if isinstance(raw, str):
                try:
                    raw = json.loads(raw)
                except Exception:
                    return []
            return raw or []

        matched = [
            SkillMatchInfo(**s) for s in _parse_skill_list(bd_raw.get("matched_skills", []))
        ]
        below = [
            SkillMatchInfo(**s) for s in _parse_skill_list(bd_raw.get("below_level_skills", []))
        ]

        candidates_out.append(CandidateMatchResponse(
            rank=rank_i,
            candidate_id=cid,
            name=detail.get("candidate_name", ""),
            current_position=detail.get("current_position", ""),
            years_of_experience=float(detail.get("years_of_experience", 0)),
            engineer_type=detail.get("engineer_type", ""),
            final_score=float(detail.get("final_score", score)),
            tier=detail.get("tier", "Partial Match"),
            score_breakdown=ScoreBreakdownResponse(
                skill_score=float(bd_raw.get("skill_score", 0)),
                semantic_score=float(bd_raw.get("semantic_score", 0)),
                position_score=float(bd_raw.get("position_score", 0)),
                special_score=float(bd_raw.get("special_score", 0)),
                final_score=float(bd_raw.get("final_score", score)),
                penalties=bd_raw.get("penalties", []),
            ),
            matched_skills=matched,
            below_level_skills=below,
            missing_skills=_parse_skill_list(bd_raw.get("missing_skills", [])),
            flags=flags,
            notice_period=detail.get("notice_period") or None,
            most_recent_company=detail.get("most_recent_company") or None,
        ))

    return MatchResultsResponse(
        jd_id=jd_id,
        jd_title=jd_data.get("title", ""),
        batch_id=batch_id,
        top_n=top_n,
        total_matched=len(candidates_out),
        candidates=candidates_out,
    )


@router.get("/{jd_id}/{candidate_id}", response_model=CandidateDetailResponse)
def get_candidate_detail(
    jd_id: str,
    candidate_id: str,
    batch_id: Optional[str] = Query(default=None),
    generate: bool = Query(default=False),
):
    if not batch_id:
        batch_id = storage.get_active_batch(jd_id)
    if not batch_id:
        raise HTTPException(404, "No match results for this JD yet.")

    detail = storage.get_candidate_detail(jd_id, batch_id, candidate_id)
    if not detail:
        raise HTTPException(404, f"Candidate {candidate_id} not found in results")

    jd_data = storage.get_jd(jd_id)

    # Check explanation cache
    cached_explanation = storage.get_explanation(jd_id, batch_id, candidate_id)
    explanation = cached_explanation
    explanation_cached = cached_explanation is not None

    # Generate if requested and not cached
    if generate and not cached_explanation and jd_data:
        try:
            explanation = explainer.generate_explanation(jd_data, detail)
            storage.save_explanation(jd_id, batch_id, candidate_id, explanation)
            explanation_cached = False
        except Exception as e:
            logger.warning(f"Explanation generation failed: {e}")
            explanation = None

    bd_raw = detail.get("score_breakdown", "{}")
    if isinstance(bd_raw, str):
        try:
            bd_raw = json.loads(bd_raw)
        except Exception:
            bd_raw = {}

    flags = detail.get("flags", [])
    if isinstance(flags, str):
        try:
            flags = json.loads(flags)
        except Exception:
            flags = []

    def _parse_skill_list(raw):
        if isinstance(raw, str):
            try:
                raw = json.loads(raw)
            except Exception:
                return []
        return raw or []

    matched = [SkillMatchInfo(**s) for s in _parse_skill_list(bd_raw.get("matched_skills", []))]
    below = [SkillMatchInfo(**s) for s in _parse_skill_list(bd_raw.get("below_level_skills", []))]

    return CandidateDetailResponse(
        rank=int(detail.get("rank", 0)),
        candidate_id=candidate_id,
        name=detail.get("candidate_name", ""),
        current_position=detail.get("current_position", ""),
        years_of_experience=float(detail.get("years_of_experience", 0)),
        engineer_type=detail.get("engineer_type", ""),
        final_score=float(detail.get("final_score", 0)),
        tier=detail.get("tier", "Partial Match"),
        score_breakdown=ScoreBreakdownResponse(
            skill_score=float(bd_raw.get("skill_score", 0)),
            semantic_score=float(bd_raw.get("semantic_score", 0)),
            position_score=float(bd_raw.get("position_score", 0)),
            special_score=float(bd_raw.get("special_score", 0)),
            final_score=float(bd_raw.get("final_score", 0)),
            penalties=bd_raw.get("penalties", []),
        ),
        matched_skills=matched,
        below_level_skills=below,
        missing_skills=_parse_skill_list(bd_raw.get("missing_skills", [])),
        flags=flags,
        notice_period=detail.get("notice_period") or None,
        most_recent_company=detail.get("most_recent_company") or None,
        explanation=explanation,
        explanation_cached=explanation_cached,
    )


@router.get("/status/{match_id}", response_model=StatusResponse)
def get_status(match_id: str):
    """
    Status check endpoint.
    Declared LAST but prefixed with literal "status/" β€” FastAPI/Starlette resolves
    static-prefix routes before variable-segment routes at the same depth only when
    both are GET and same length. To be safe this is also on the status_router
    with its own prefix (see main.py include). Use /api/v1/status/{match_id}.
    """
    status = storage.get_match_status(match_id)
    if not status:
        raise HTTPException(404, f"Match {match_id} not found")
    return StatusResponse(
        match_id=match_id,
        status=status.get("status", "unknown"),
        progress=float(status["progress"]) if "progress" in status else None,
        message=status.get("message"),
        completed_at=status.get("completed_at"),
    )


# Separate router for status β€” avoids /{jd_id} shadowing /status/{match_id}
status_router = APIRouter(prefix="/api/v1/status", tags=["status"])


@status_router.get("/{match_id}", response_model=StatusResponse)
def get_status_v2(match_id: str):
    return get_status(match_id)