"""Schemas — Phase 5 final evaluation (orchestrates text/voice/video) & reporting."""

from enum import Enum
from typing import Any
from uuid import UUID

from pydantic import AliasChoices, BaseModel, ConfigDict, Field, field_validator, model_validator

from app.schemas.common import StubMeta
from app.schemas.interviews import InterviewMode


class ScoreProvenance(str, Enum):
    SUPPLIED = "supplied"
    CALCULATED = "calculated"
    CALCULATED_FROM_SUPPLIED = "calculated_from_supplied"
    UNAVAILABLE = "unavailable"


# Documented default when Platform lists a skill but omits required_level.
DEFAULT_REQUIRED_SKILL_LEVEL = 0.75


class CategoryWeight(BaseModel):
    key: str = Field(..., min_length=1)
    weight: float = Field(default=1.0, ge=0.0, le=10.0)
    label: str | None = None


class SkillTarget(BaseModel):
    """Explicit skill requirement — preferred over inventing levels."""

    skill: str = Field(..., min_length=1)
    required_level: float | None = Field(
        default=None,
        ge=0.0,
        le=1.0,
        description=(
            "Required demonstrated level 0–1. When omitted, uses documented "
            f"default {DEFAULT_REQUIRED_SKILL_LEVEL}."
        ),
    )


class TranscriptTurnIn(BaseModel):
    turn_id: str | None = None
    role: str = Field(..., description="interviewer | candidate")
    text: str = ""
    timestamp_ms: int | None = None


class QaItemIn(BaseModel):
    """One interview question with at most one media answer (voice or video)."""

    model_config = ConfigDict(populate_by_name=True)

    question_id: str | None = None
    question: str = Field(..., min_length=1)
    answer: str = Field(
        default="",
        description="Candidate text answer (text mode, or filled after STT for voice/video)",
    )
    turn_index: int | None = Field(default=None, ge=0)
    category_keys: list[str] = Field(
        default_factory=list,
        description=(
            "Rubric/category keys this question maps to (e.g. correctness, depth). "
            "Used for category aggregation when dimension scores are sparse."
        ),
    )
    skill_tags: list[str] = Field(
        default_factory=list,
        description="Skills this question assesses — used for skill-gap evidence mapping",
    )
    audio_base64: str | None = Field(
        default=None,
        description=(
            "Exactly one voice answer for this question (base64). "
            "Mutually exclusive with audio_source_url. interview_mode=voice."
        ),
    )
    audio_source_url: str | None = Field(
        default=None,
        description=(
            "Exactly one voice answer URL for this question. "
            "Mutually exclusive with audio_base64. interview_mode=voice."
        ),
    )
    video_base64: str | None = Field(
        default=None,
        description=(
            "Exactly one video answer for this question (base64). "
            "Mutually exclusive with video_source_url. interview_mode=video."
        ),
    )
    video_source_url: str | None = Field(
        default=None,
        description=(
            "Exactly one video answer URL for this question. "
            "Mutually exclusive with video_base64. interview_mode=video."
        ),
    )

    @field_validator("answer", mode="before")
    @classmethod
    def coerce_none_answer(cls, v: object) -> object:
        if v is None:
            return ""
        return v

    def has_voice_media(self) -> bool:
        return bool(self.audio_base64) or bool(self.audio_source_url)

    def has_video_media(self) -> bool:
        return bool(self.video_base64) or bool(self.video_source_url)

    @model_validator(mode="after")
    def _at_most_one_audio_and_one_video(self) -> "QaItemIn":
        if self.audio_base64 and self.audio_source_url:
            raise ValueError(
                "Provide exactly one of audio_base64 or audio_source_url per question"
            )
        if self.video_base64 and self.video_source_url:
            raise ValueError(
                "Provide exactly one of video_base64 or video_source_url per question"
            )
        return self


class TurnScoreIn(BaseModel):
    """Trusted Platform turn score (provenance=supplied)."""

    question_id: str | None = None
    turn_index: int | None = Field(default=None, ge=0)
    score: float = Field(..., ge=0.0, le=1.0)
    score_band: str | None = None
    dimensions: dict[str, float] = Field(default_factory=dict)
    skill_tags: list[str] = Field(
        default_factory=list,
        description="Optional skill mappings for this turn when qa_items omit skill_tags",
    )
    strengths: list[str] = Field(default_factory=list)
    weaknesses: list[str] = Field(default_factory=list)
    improvement_feedback: list[str] = Field(default_factory=list)
    explanation: str | None = None
    provenance: ScoreProvenance = ScoreProvenance.SUPPLIED

    @field_validator("dimensions")
    @classmethod
    def clamp_dims(cls, v: dict[str, float]) -> dict[str, float]:
        out: dict[str, float] = {}
        for k, raw in (v or {}).items():
            try:
                out[str(k)] = max(0.0, min(1.0, float(raw)))
            except (TypeError, ValueError):
                continue
        return out

    @field_validator("provenance")
    @classmethod
    def only_supplied_or_calculated(cls, v: ScoreProvenance) -> ScoreProvenance:
        if v not in {ScoreProvenance.SUPPLIED, ScoreProvenance.CALCULATED}:
            raise ValueError(
                "turn_scores provenance must be 'supplied' or 'calculated'"
            )
        return v


class MediaEvidenceIn(BaseModel):
    """Authorized media-analysis outputs from Platform (never invent scores)."""

    audio_analysis: dict[str, Any] | None = None
    video_intelligence: dict[str, Any] | None = None
    behavioral_analysis: dict[str, Any] | None = None
    communication_analysis: dict[str, Any] | None = None


# Swagger / OpenAPI Try-it-out bodies (text / voice / video).
FINAL_EVALUATION_OPENAPI_EXAMPLES: dict[str, dict[str, Any]] = {
    "text": {
        "summary": "Text interview (answers + optional supplied scores)",
        "value": {
            "correlation_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
            "interview_id": "int-acme-jane-001",
            "interview_mode": "text",
            "role_title": "Backend Engineer",
            "job_description": (
                "We are hiring a Backend Engineer to design and operate APIs, "
                "data pipelines, and cloud services. Requirements: Python, SQL, "
                "distributed systems, 3+ years experience."
            ),
            "company_name": "Acme Corp",
            "candidate_id": "cand-jane-001",
            "candidate_name": "Jane Doe",
            "category_weights": [
                {"key": "correctness", "weight": 2.0, "label": "Correctness"},
                {"key": "depth", "weight": 1.0, "label": "Depth"},
                {"key": "relevance", "weight": 1.0, "label": "Relevance"},
            ],
            "required_skills": ["Python", "SQL", "API design"],
            "skill_targets": [
                {"skill": "Python", "required_level": 0.75},
                {"skill": "SQL", "required_level": 0.7},
            ],
            "qa_items": [
                {
                    "question_id": "q-cache-design-001",
                    "question": "How would you design a cache for a high-read API?",
                    "answer": (
                        "I would use cache-aside with Redis, short TTLs for volatile "
                        "keys, and add hit-rate plus p99 latency dashboards before "
                        "full rollout."
                    ),
                    "turn_index": 0,
                    "category_keys": ["correctness", "depth", "relevance"],
                    "skill_tags": ["Python", "API design"],
                }
            ],
            "turn_scores": [
                {
                    "question_id": "q-cache-design-001",
                    "turn_index": 0,
                    "score": 0.85,
                    "score_band": "strong",
                    "dimensions": {
                        "correctness": 0.9,
                        "depth": 0.8,
                        "relevance": 0.85,
                    },
                    "skill_tags": ["Python", "API design"],
                    "strengths": ["Clear cache-aside plan", "Mentions monitoring"],
                    "weaknesses": ["Could discuss failure modes more"],
                    "improvement_feedback": [
                        "Cover stampede protection and invalidation strategy"
                    ],
                    "explanation": "Solid Redis cache-aside design with observability.",
                    "provenance": "supplied",
                }
            ],
            "include_answer_feedback": False,
            "include_details": False,
            "language": "en",
        },
    },
    "voice": {
        "summary": "Voice: one audio answer per question → STT → score",
        "value": {
            "correlation_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
            "interview_id": "int-acme-jane-voice-001",
            "interview_mode": "voice",
            "role_title": "Backend Engineer",
            "job_description": (
                "We are hiring a Backend Engineer to design and operate APIs."
            ),
            "company_name": "Acme Corp",
            "candidate_id": "cand-jane-001",
            "candidate_name": "Jane Doe",
            "required_skills": ["Python", "SQL"],
            "qa_items": [
                {
                    "question_id": "q-cache-design-001",
                    "question": "How would you design a cache for a high-read API?",
                    "answer": "",
                    "turn_index": 0,
                    "skill_tags": ["Python"],
                    "audio_source_url": (
                        "https://www.voiptroubleshooter.com/open_speech/american/"
                        "OSR_us_000_0010_8k.wav"
                    ),
                },
                {
                    "question_id": "q-sql-indexes-002",
                    "question": "How do you choose PostgreSQL indexes?",
                    "answer": "",
                    "turn_index": 1,
                    "skill_tags": ["SQL"],
                    "audio_source_url": (
                        "https://www.voiptroubleshooter.com/open_speech/american/"
                        "OSR_us_000_0010_8k.wav"
                    ),
                },
            ],
            "include_details": False,
            "language": "en",
        },
    },
    "video": {
        "summary": "Video: one video answer per question → transcript → score",
        "value": {
            "correlation_id": "3fa85f64-5717-4562-b3fc-2c963f66afa6",
            "interview_id": "int-acme-jane-video-001",
            "interview_mode": "video",
            "role_title": "Backend Engineer",
            "job_description": (
                "We are hiring a Backend Engineer to design and operate APIs."
            ),
            "company_name": "Acme Corp",
            "candidate_id": "cand-jane-001",
            "candidate_name": "Jane Doe",
            "required_skills": ["Python", "SQL"],
            "qa_items": [
                {
                    "question_id": "q-cache-design-001",
                    "question": "How would you design a cache for a high-read API?",
                    "answer": "",
                    "turn_index": 0,
                    "skill_tags": ["Python"],
                    "video_source_url": "https://example.com/sample-q1.mp4",
                },
                {
                    "question_id": "q-sql-indexes-002",
                    "question": "How do you choose PostgreSQL indexes?",
                    "answer": "",
                    "turn_index": 1,
                    "skill_tags": ["SQL"],
                    "video_source_url": "https://example.com/sample-q2.mp4",
                },
            ],
            "consent_given": True,
            "include_details": False,
            "language": "en",
        },
    },
}


class FinalEvaluationRequest(BaseModel):
    """POST /api/v1/interviews/final-evaluation — orchestrates by interview_mode and persists."""

    model_config = ConfigDict(
        populate_by_name=True,
        json_schema_extra={
            "example": FINAL_EVALUATION_OPENAPI_EXAMPLES["text"]["value"],
        },
    )

    correlation_id: UUID | None = None
    interview_id: str = Field(
        ...,
        min_length=1,
        description="Platform interview id (required for persistence + PDF)",
    )
    interview_mode: InterviewMode = Field(
        ...,
        validation_alias=AliasChoices("interview_mode", "interview_type"),
        description="text | voice | video (alias: interview_type)",
    )
    role_title: str = Field(..., min_length=1)
    job_description: str | None = None
    company_name: str | None = None
    candidate_id: str = Field(
        ...,
        min_length=1,
        description="Platform candidate id (required for persistence + PDF)",
    )
    candidate_name: str | None = None
    category_weights: list[CategoryWeight] = Field(default_factory=list)
    required_skills: list[str] = Field(
        default_factory=list,
        description="Skill names; prefer skill_targets for explicit required levels",
    )
    skill_targets: list[SkillTarget] = Field(
        default_factory=list,
        description="Explicit skill requirements with optional required_level",
    )
    transcript: list[TranscriptTurnIn] = Field(default_factory=list)
    qa_items: list[QaItemIn] = Field(
        default_factory=list,
        validation_alias=AliasChoices("qa_items", "questions_answers"),
    )
    turn_scores: list[TurnScoreIn] = Field(
        default_factory=list,
        description="Trusted Platform scores; aggregated as-is when valid",
    )
    media_evidence: MediaEvidenceIn | None = None
    consent_given: bool = Field(
        default=False,
        description="Required true for video-intelligence biometric processing",
    )
    include_answer_feedback: bool = Field(
        default=False,
        description="When true (or include_details), attach per-answer feedback in details",
    )
    include_details: bool = Field(
        default=False,
        description=(
            "When true, include diagnostics: per-answer scores, provenance, "
            "aggregation metadata, media metrics, and evidence. Default response "
            "is a concise recruiter summary only."
        ),
    )
    language: str = Field(default="en", min_length=2, max_length=10)
    options: dict[str, Any] = Field(default_factory=dict)

    @model_validator(mode="after")
    def _require_evidence_and_unique_ids(self) -> "FinalEvaluationRequest":
        if not self.qa_items and not self.transcript and not self.turn_scores:
            raise ValueError(
                "Provide qa_items and/or transcript and/or turn_scores "
                "for final evaluation"
            )
        seen: set[str] = set()
        for item in self.qa_items:
            qid = (item.question_id or "").strip()
            if not qid:
                continue
            if qid in seen:
                raise ValueError(f"Duplicate question_id in qa_items: {qid}")
            seen.add(qid)
            if self.interview_mode == InterviewMode.VOICE:
                has_text = bool((item.answer or "").strip())
                if not item.has_voice_media() and not has_text:
                    raise ValueError(
                        f"Voice QA {qid or item.question[:32]!r} needs "
                        "one audio_base64/audio_source_url or answer text"
                    )
            if self.interview_mode == InterviewMode.VIDEO:
                has_text = bool((item.answer or "").strip())
                if not item.has_video_media() and not has_text:
                    raise ValueError(
                        f"Video QA {qid or item.question[:32]!r} needs "
                        "one video_base64/video_source_url or answer text"
                    )
        if self.interview_mode == InterviewMode.VIDEO and self.qa_items:
            needs_vi = any(
                item.has_video_media() and not (item.answer or "").strip()
                for item in self.qa_items
            )
            if needs_vi and not self.consent_given:
                raise ValueError(
                    "consent_given=true is required when video media will be analyzed"
                )
        weight_keys: set[str] = set()
        for w in self.category_weights:
            key = w.key.strip()
            if key in weight_keys:
                raise ValueError(f"Duplicate category weight key: {key}")
            weight_keys.add(key)
        return self


class QuestionScoreItem(BaseModel):
    question_id: str | None = None
    question_text: str | None = None
    turn_index: int
    score: float | None = None
    score_band: str | None = None
    dimensions: dict[str, float] = Field(default_factory=dict)
    enriched_dimension_keys: list[str] = Field(
        default_factory=list,
        description="Dimension keys filled by internal rubric scoring without replacing total",
    )
    category_keys: list[str] = Field(default_factory=list)
    skill_tags: list[str] = Field(default_factory=list)
    strengths: list[str] = Field(default_factory=list)
    weaknesses: list[str] = Field(default_factory=list)
    improvement_feedback: list[str] = Field(default_factory=list)
    explanation: str | None = Field(
        default=None,
        description="Score rationale for this answer (why the score was assigned)",
    )
    ai_explanation: str | None = Field(
        default=None,
        description=(
            "Review-UI concept guide: how this question should be answered "
            "(intended approach / best practice) — distinct from score explanation"
        ),
    )
    provenance: ScoreProvenance = ScoreProvenance.CALCULATED


class QuestionReviewBrief(BaseModel):
    """Per-question Review tab payload (question + response + AI Explanation)."""

    question_id: str | None = None
    turn_index: int = 0
    question: str | None = None
    answer: str | None = None
    score: float | None = None
    score_band: str | None = None
    ai_explanation: str | None = Field(
        default=None,
        description="How this question should be answered / concept explanation",
    )


class CategoryScore(BaseModel):
    key: str
    label: str
    score: float | None = None
    weight: float = 1.0
    effective_weight: float | None = Field(
        default=None,
        description="Normalized weight used in overall (None when category unavailable)",
    )
    sample_size: int = 0
    evidence: list[str] = Field(default_factory=list)
    provenance: ScoreProvenance = ScoreProvenance.UNAVAILABLE


class AggregatedScores(BaseModel):
    overall_score: float | None = None
    max_score: float = 1.0
    question_count: int = 0
    category_scores: list[CategoryScore] = Field(default_factory=list)
    question_scores: list[QuestionScoreItem] = Field(default_factory=list)
    weights_configured: dict[str, float] = Field(default_factory=dict)
    weights_effective: dict[str, float] = Field(default_factory=dict)
    missing_categories: list[str] = Field(default_factory=list)
    fallback: str | None = Field(
        default=None,
        description=(
            "Documented overall fallback when category mapping unavailable, "
            "e.g. mean_question_scores"
        ),
    )
    # Backward-compat alias of weights_effective for older clients
    weights_used: dict[str, float] = Field(default_factory=dict)
    overall_provenance: ScoreProvenance = ScoreProvenance.UNAVAILABLE


class MetricAssessment(BaseModel):
    key: str
    label: str
    score: float | None = None
    provenance: ScoreProvenance = ScoreProvenance.UNAVAILABLE
    detail: str | None = None
    evidence: dict[str, Any] = Field(default_factory=dict)


class FinalReport(BaseModel):
    summary: str
    performance_overview: str | None = None
    strengths: list[str] = Field(default_factory=list)
    weaknesses: list[str] = Field(default_factory=list)
    actionable_recommendations: list[str] = Field(default_factory=list)
    answer_level_feedback: list[QuestionScoreItem] = Field(default_factory=list)
    markdown: str | None = None


class SkillGapFinding(BaseModel):
    skill: str
    required_level: float | None = None
    demonstrated_level: float | None = None
    gap: float | None = None
    priority: str = "medium"
    needs_more_evidence: bool = False
    evidence: str | None = None
    improvement_suggestions: list[str] = Field(default_factory=list)
    provenance: ScoreProvenance = ScoreProvenance.UNAVAILABLE


class SkillGapAnalysis(BaseModel):
    overall_readiness: float | None = None
    readiness_provenance: ScoreProvenance = ScoreProvenance.UNAVAILABLE
    default_required_level: float = DEFAULT_REQUIRED_SKILL_LEVEL
    strengths: list[str] = Field(default_factory=list)
    gaps: list[SkillGapFinding] = Field(default_factory=list)
    recommended_prep_focus: list[str] = Field(default_factory=list)
    skill_scores: list[MetricAssessment] = Field(default_factory=list)


class HiringFitRecommendation(BaseModel):
    hiring_fit_score: float | None = None
    hiring_fit_label: str
    recommendation: str
    formula: str | None = Field(
        default=None,
        description="Transparent reproducible formula used for hiring_fit_score",
    )
    supporting_evidence: list[str] = Field(default_factory=list)
    limitations: list[str] = Field(default_factory=list)
    missing_information: list[str] = Field(default_factory=list)
    requires_human_review: bool = True
    human_review_note: str = (
        "AI recommendation only — final hiring decisions remain under human review."
    )


class SkillStatus(str, Enum):
    ASSESSED = "assessed"
    NEEDS_IMPROVEMENT = "needs_improvement"
    NOT_ASSESSED = "not_assessed"


class SkillAssessmentBrief(BaseModel):
    skill: str
    score: float | None = None
    status: SkillStatus
    required_level: float | None = None


class CategoryScoreBrief(BaseModel):
    key: str
    label: str
    score: float | None = None


class RecommendationBrief(BaseModel):
    label: str
    action: str
    reason: str
    score: float | None = None
    requires_human_review: bool = True


class FinalEvaluationDetails(BaseModel):
    """Optional diagnostics — omit from default recruiter response."""

    max_score: float = 1.0
    overall_provenance: ScoreProvenance | None = None
    aggregation_fallback: str | None = None
    aggregated: AggregatedScores | None = None
    report: FinalReport | None = None
    skill_gap: SkillGapAnalysis | None = None
    hiring_fit: HiringFitRecommendation | None = None
    behavioral: MetricAssessment | None = None
    communication: MetricAssessment | None = None
    text_communication: list[MetricAssessment] = Field(default_factory=list)
    media_metrics: list[MetricAssessment] = Field(default_factory=list)
    degraded: bool = False


class FinalEvaluationResponse(StubMeta):
    """Concise recruiter-facing final evaluation (default)."""

    correlation_id: UUID | None = None
    interview_id: str | None = None
    interview_mode: InterviewMode
    candidate_id: str | None = None
    candidate_name: str | None = None
    company_name: str | None = None
    role_title: str
    evaluation_id: str | None = None
    evaluation_status: str | None = Field(
        default=None,
        description="pending | processing | completed | failed",
    )
    evaluation_version: int | None = None
    processing_stage: str | None = None
    error_code: str | None = None
    question_count: int = 0
    overall_score: float | None = None
    summary: str = ""
    strengths: list[str] = Field(default_factory=list, max_length=3)
    improvement_areas: list[str] = Field(default_factory=list, max_length=3)
    skills: list[SkillAssessmentBrief] = Field(default_factory=list)
    categories: list[CategoryScoreBrief] = Field(default_factory=list)
    questions: list[QuestionReviewBrief] = Field(
        default_factory=list,
        description=(
            "Per-question Review items: question, candidate answer, score, "
            "and ai_explanation (how it should be answered)"
        ),
    )
    recommendation: RecommendationBrief | None = None
    warnings: list[str] = Field(default_factory=list)
    details: FinalEvaluationDetails | None = Field(
        default=None,
        description="Present only when request.include_details=true",
    )


class FinalEvaluationStatusResponse(StubMeta):
    """GET /api/v1/interviews/final-evaluation/status"""

    candidate_id: str
    interview_id: str
    evaluation_id: str | None = None
    evaluation_status: str | None = None
    processing_stage: str | None = None
    evaluation_version: int | None = None
    interview_mode: str | None = None
    overall_score: float | None = None
    final_recommendation: dict[str, Any] | None = None
    error_code: str | None = None
    error_message: str | None = None
