from __future__ import annotations

import os

from google import genai

from .models import CandidateProfile, JobDescription, MatchScore


class RelevanceScorer:
    """
    Uses Gemini to evaluate candidate–job fit before proceeding with
    expensive tailoring and application steps.
    """

    def score(self, candidate: CandidateProfile, job: JobDescription) -> MatchScore:
        if not os.environ.get("GEMINI_API_KEY"):
            raise ValueError("GEMINI_API_KEY environment variable is missing.")

        client = genai.Client()

        prompt = f"""
        You are an expert recruiting analyst.
        Evaluate how well the following candidate matches this job description.

        JOB:
        Title: {job.title}
        Company: {job.company or 'Unknown'}
        Required Skills: {', '.join(job.required_skills)}
        Nice-to-Have: {', '.join(job.nice_to_have_skills)}
        Responsibilities: {', '.join(job.responsibilities)}

        CANDIDATE:
        Headline: {candidate.headline}
        Years of Experience: {candidate.years_experience}
        Skills: {', '.join(candidate.skills)}
        Industries: {', '.join(candidate.industries)}

        Return:
        - score: An integer from 0 to 100 representing how well the candidate matches (100 = perfect fit).
        - reasoning: A brief 1-2 sentence explanation of the score.
        - apply_recommendation: true if the candidate should apply, false if it's a poor fit.
        """

        response = client.models.generate_content(
            model="gemini-2.5-flash",
            contents=prompt,
            config=genai.types.GenerateContentConfig(
                response_mime_type="application/json",
                response_schema=MatchScore,
                temperature=0.3,
            ),
        )
        return response.parsed
