"""Adaptive interview follow-ups + real-time answer evaluation."""

from app.schemas.common import JobStatus
from app.schemas.interviews import (
    EvaluateAnswerRequest,
    EvaluateAnswerResponse,
    FollowUpQuestion,
    FollowUpRequest,
    FollowUpResponse,
)
from app.services.ai_generate import generate_json


class InterviewsService:
    async def generate_follow_up(self, payload: FollowUpRequest) -> FollowUpResponse:
        system = (
            "You are an adaptive interviewer. Decide if a follow-up is needed. "
            "Return JSON: {\"should_follow_up\":bool,\"next_action\":\"continue|wrap_up|skip\","
            "\"follow_ups\":[{\"id\",\"text\",\"rationale\",\"skill_tags\":[]}]}"
        )
        user = (
            f"Role: {payload.role_title}\nPersona: {payload.persona.value}\n"
            f"Mode: {payload.mode.value}\nPlanned Q: {payload.planned_question}\n"
            f"Answer: {payload.candidate_answer}\n"
            f"JD: {payload.job_description or 'n/a'}\n"
            f"Skills focus: {payload.skills_focus}\n"
            f"Max follow-ups: {payload.max_follow_ups}"
        )

        def local() -> dict:
            return {
                "should_follow_up": True,
                "next_action": "continue",
                "follow_ups": [
                    {
                        "id": "fu-1",
                        "text": (
                            f"Can you go deeper on how you applied that for "
                            f"{payload.role_title} — what trade-offs did you make?"
                        ),
                        "rationale": "Probe depth and decision-making from the answer.",
                        "skill_tags": payload.skills_focus[:3] or ["depth"],
                    }
                ][: payload.max_follow_ups],
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        follow_ups = [
            FollowUpQuestion(
                id=str(f.get("id", f"fu-{i}")),
                text=str(f.get("text", "")),
                rationale=f.get("rationale"),
                skill_tags=list(f.get("skill_tags") or []),
            )
            for i, f in enumerate(data.get("follow_ups") or [])
            if isinstance(f, dict) and f.get("text")
        ]
        return FollowUpResponse(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Follow-up generated via {provider}",
            should_follow_up=bool(data.get("should_follow_up", bool(follow_ups))),
            follow_ups=follow_ups,
            next_action=str(data.get("next_action") or "continue"),
        )

    async def evaluate_answer(
        self, payload: EvaluateAnswerRequest
    ) -> EvaluateAnswerResponse:
        system = (
            "Evaluate one live interview answer. Return JSON: "
            "{\"score\":0-1,\"feedback\",\"strengths\":[],\"gaps\":[],"
            "\"next_action\":\"continue|follow_up|wrap_up\"}"
        )
        user = (
            f"Role: {payload.role_title}\nPersona: {payload.persona.value}\n"
            f"Q: {payload.question}\nA: {payload.candidate_answer}\n"
            f"JD: {payload.job_description}\nSkills: {payload.skills_focus}"
        )

        def local() -> dict:
            length = len(payload.candidate_answer.strip())
            score = 0.45 if length < 40 else 0.7 if length < 200 else 0.85
            return {
                "score": score,
                "feedback": "Answer captured. Add concrete metrics where possible.",
                "strengths": ["Relevant to the question"] if length > 20 else [],
                "gaps": ["Needs more evidence / examples"] if score < 0.75 else [],
                "next_action": "follow_up" if score < 0.75 else "continue",
            }

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=local
        )
        return EvaluateAnswerResponse(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Answer evaluated via {provider}",
            score=data.get("score"),
            max_score=1.0,
            feedback=data.get("feedback"),
            strengths=list(data.get("strengths") or []),
            gaps=list(data.get("gaps") or []),
            next_action=str(data.get("next_action") or "continue"),
        )
