"""Search & Match API Routes — /v1/search/* Endpoints: GET /v1/search/talent — Search talents (free: keyword, masked | premium: AI, full) POST /v1/search/ai — AI-powered search (costs coins) POST /v1/search/unlock — Unlock candidate identity (costs coins) GET /v1/search/unlocks — Get unlock history GET /v1/search/balance — Check employer credit balance Free tier: - Keyword search on name, skills, location - Masked profiles (no name, email, phone) - 10 results max - No AI matching """ from typing import List from fastapi import APIRouter, Depends, Query, Request from loguru import logger from sqlalchemy.ext.asyncio import AsyncSession from app.database import get_db from app.schemas.search import ( AdvancedSearchRequest, AISearchResponse, SearchRequest, SearchResponse, UnlockRequest, UnlockResponse, UnlockHistoryItem, ) from app.services.search_service import ( ai_search, get_employer_balance, get_unlock_history, keyword_search, unlock_candidate, ) from app.utils.errors import ErrorCode, error_response, raise_error router = APIRouter(prefix="/v1/search", tags=["Search & Match"]) @router.get( "/talent", response_model=SearchResponse, summary="Search talents", description="""Search talents by keywords, category, location, sector, and score. Free tier (default): masked profiles, 10 results max, no AI matching. Set `use_ai=true` for AI-powered matching (requires authentication + credits). """, ) async def search_talents( request: Request, db: AsyncSession = Depends(get_db), query: str = Query("", description="Search keywords"), category: str = Query(None, description="Filter by AI category"), location: str = Query(None, description="Filter by city/province"), sector: str = Query(None, description="Filter by sector"), min_score: int = Query(None, ge=0, le=100), skills: str = Query(None, description="Comma-separated skills"), page: int = Query(1, ge=1), limit: int = Query(10, ge=1, le=50), use_ai: bool = Query(False, description="Enable AI matching (premium)"), ): """Search talents with filters.""" result = await keyword_search( db, query=query, category=category, location=location, sector=sector, min_score=min_score, skills=skills, page=page, limit=limit, use_ai=use_ai, ) return result @router.post( "/ai", response_model=AISearchResponse, summary="AI-powered talent search", description="Advanced AI semantic search. Costs credits. Requires authentication.", ) async def advanced_search( request: Request, body: AdvancedSearchRequest, db: AsyncSession = Depends(get_db), ): """AI-powered search with semantic matching.""" # Get employer email from JWT payload = getattr(request.state, "user", None) if payload is None: raise_error("Authentication required for AI search.", ErrorCode.TOKEN_INVALID, 401) if payload.get("role") not in ("employer", "admin"): raise_error("Only employers can use AI search.", ErrorCode.NOT_AUTHORIZED, 403) result = await ai_search( db, query=body.query, employer_email=payload["email"], required_skills=body.required_skills, sector=body.sector, location=body.location, limit=body.limit, ) return result @router.post( "/unlock", response_model=UnlockResponse, summary="Unlock candidate identity", description="Deduct coins to reveal candidate identity. Costs 3-5 coins based on seniority.", ) async def unlock( request: Request, body: UnlockRequest, db: AsyncSession = Depends(get_db), ): """Unlock candidate identity (costs coins).""" payload = getattr(request.state, "user", None) if payload is None: raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401) if payload.get("role") not in ("employer", "admin"): raise_error("Only employers can unlock candidates.", ErrorCode.NOT_AUTHORIZED, 403) result = await unlock_candidate( db, employer_email=payload["email"], candidate_id=body.candidate_id, query=body.query or "", ) return result @router.get( "/unlocks", response_model=List[UnlockHistoryItem], summary="Get unlock history", description="List all candidates this employer has unlocked.", ) async def unlock_history( request: Request, db: AsyncSession = Depends(get_db), ): """Get unlock history for the authenticated employer.""" payload = getattr(request.state, "user", None) if payload is None: raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401) return await get_unlock_history(db, payload["email"]) @router.get( "/balance", summary="Check credit balance", description="Get current credit balance and tier information.", ) async def balance( request: Request, db: AsyncSession = Depends(get_db), ): """Check employer credit balance.""" payload = getattr(request.state, "user", None) if payload is None: raise_error("Authentication required.", ErrorCode.TOKEN_INVALID, 401) if payload.get("role") not in ("employer", "admin"): raise_error("Only employers can check balance.", ErrorCode.NOT_AUTHORIZED, 403) return await get_employer_balance(db, payload["email"])