from __future__ import annotations

import os
from ..models import JobDescription


class JobDescriptionParserAgent:
    """
    Extracts structured JobDescription fields from raw text using Gemini.
    """

    def parse(
        self,
        raw_text: str,
        *,
        url: str | None = None,
        title_override: str | None = None,
    ) -> JobDescription:
        if not os.environ.get("GEMINI_API_KEY"):
            raise ValueError("GEMINI_API_KEY environment variable is missing.")

        from google import genai
        client = genai.Client()

        prompt = f"""
        Extract the following job description into a structured format.
        
        Raw text:
        {raw_text}
        
        If the company, location, seniority, or salary range are not explicitly mentioned, omit them (or return null).
        Extract responsibilities, required skills, and nice-to-have skills as concise bullet points.
        Ideally infer the title if it's obvious, taking care to strip conversational filler like "We are hiring a...".
        """

        response = client.models.generate_content(
            model='gemini-2.5-flash',
            contents=prompt,
            config=genai.types.GenerateContentConfig(
                response_mime_type="application/json",
                response_schema=JobDescription,
                temperature=0.2,
            ),
        )

        job_desc = response.parsed
        job_desc.raw_text = raw_text.strip()
        job_desc.url = url
        if title_override:
            job_desc.title = title_override
            
        return job_desc
