from __future__ import annotations

import os
from typing import List
from pydantic import BaseModel

from ..models import CandidateProfile, JobDescription, PortfolioSuggestion

class PortfolioSuggestionsResponse(BaseModel):
    suggestions: List[PortfolioSuggestion]

class PortfolioCoachAgent:
    """
    Suggests concrete portfolio improvements to better match a target job using Gemini.
    """

    def suggest(self, candidate: CandidateProfile, job: JobDescription) -> List[PortfolioSuggestion]:
        if not os.environ.get("GEMINI_API_KEY"):
            # Fallback or warning if no key is present. To keep it simple, we raise an error.
            raise ValueError("GEMINI_API_KEY environment variable is missing.")

        from google import genai
        client = genai.Client()

        achievements_str = "\n".join(f"- {a}" for a in candidate.achievements)
        
        prompt = f"""
        You are an expert career and portfolio coach.
        Review the following candidate profile and job description, then suggest 3 to 4 high-value, actionable portfolio improvements to help the candidate stand out.
        
        JOB DESCRIPTION:
        Title: {job.title}
        Company: {job.company or 'Unknown'}
        Details: {job.raw_text}
        
        CANDIDATE:
        Name: {candidate.name}
        Headline: {candidate.headline}
        Years of Experience: {candidate.years_experience}
        Skills: {', '.join(candidate.skills)}
        Achievements:
        {achievements_str}
        
        Each suggestion must include:
        - title: A short imperative title (e.g., "Build a React Dashboard")
        - description: Details on what the project should demonstrate and how it relates to the job requirements.
        - priority: "high", "medium", or "low".
        """

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

