from __future__ import annotations

import os
from typing import List
from pydantic import BaseModel

from ..models import (
    CandidateProfile,
    InterviewQuestion,
    InterviewSession,
    InterviewTurn,
    JobDescription,
)


class QuestionListResponse(BaseModel):
    questions: List[InterviewQuestion]

class FeedbackResponse(BaseModel):
    feedback: str
    score: int


class InterviewCoachAgent:
    """
    Generates interview questions and lightweight feedback for a mock interview using Gemini.
    """

    def _get_client(self):
        if not os.environ.get("GEMINI_API_KEY"):
            raise ValueError("GEMINI_API_KEY environment variable is missing.")
        from google import genai
        return genai.Client()

    def create_session(self, candidate: CandidateProfile, job: JobDescription) -> InterviewSession:
        questions = self._generate_questions(candidate, job)
        turns = [InterviewTurn(question=q) for q in questions]
        return InterviewSession(job=job, candidate=candidate, turns=turns)

    def review_answers(self, session: InterviewSession, answers: List[str]) -> InterviewSession:
        for turn, answer in zip(session.turns, answers):
            turn.candidate_answer = answer
            if answer.strip():
                turn.feedback, turn.score = self._give_feedback(session.job, turn.question, answer)
            else:
                turn.feedback = "No answer provided."
                turn.score = 1
        return session

    # --- internals ---

    def _generate_questions(
        self, candidate: CandidateProfile, job: JobDescription
    ) -> List[InterviewQuestion]:
        client = self._get_client()

        prompt = f"""
        You are an expert technical interviewer hiring for:
        Role: {job.title}
        Company: {job.company or 'Unknown'}
        Required Skills: {', '.join(job.required_skills)}
        
        Candidate Background:
        Headline: {candidate.headline}
        Years of Exp: {candidate.years_experience}
        Skills: {', '.join(candidate.skills)}
        
        Generate exactly 4 challenging, realistic mock interview questions.
        Provide a variety of categories (e.g., "behavioral", "technical", "system design", "role_alignment").
        Each question should include 'focus_areas' identifying what a strong answer should cover.
        """
        
        from google import genai
        response = client.models.generate_content(
            model='gemini-2.5-flash',
            contents=prompt,
            config=genai.types.GenerateContentConfig(
                response_mime_type="application/json",
                response_schema=QuestionListResponse,
                temperature=0.7,
            ),
        )
        return response.parsed.questions

    def _give_feedback(self, job: JobDescription, question: InterviewQuestion, answer: str) -> tuple[str, int]:
        client = self._get_client()

        prompt = f"""
        You are an expert technical interviewer evaluating a candidate's answer.
        Role: {job.title}
        
        Question Category: {question.category}
        Question: {question.question}
        Focus Areas: {', '.join(question.focus_areas)}
        
        Candidate's Answer:
        "{answer}"
        
        Provide constructive feedback and a score from 1 to 5, where:
        1 = Very Poor
        2 = Below Average
        3 = Average / Acceptable
        4 = Strong
        5 = Outstanding / Hired
        
        Your feedback should point out strengths and areas for improvement, especially mentioning the focus areas.
        """

        from google import genai
        response = client.models.generate_content(
            model='gemini-2.5-flash',
            contents=prompt,
            config=genai.types.GenerateContentConfig(
                response_mime_type="application/json",
                response_schema=FeedbackResponse,
                temperature=0.5,
            ),
        )
        parsed = response.parsed
        return parsed.feedback, parsed.score

