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)