"""Candidate Performance read/write orchestration (no LLM on GET)."""

from __future__ import annotations

import logging
from typing import Any
from uuid import uuid4

from fastapi import HTTPException, status

from app.deps import PlatformActorContext
from app.schemas.candidate_performance import (
    AiDimensionScores,
    AiPerformanceIngestRequest,
    AssessmentAttemptIngestRequest,
    AssessmentAttemptItem,
    CandidateAiPerformanceResponse,
    CandidateAssessmentsPerformanceResponse,
    CandidateOverallPerformanceResponse,
    HiringRecommendation,
    PerformanceScoreCard,
)
from app.schemas.common import JobStatus
from app.services.talent import performance_store as store
from app.services.talent.performance_scoring import (
    clamp_score_100,
    compute_overall_performance,
    map_interview_dimensions,
)

logger = logging.getLogger(__name__)


def _actor_company(actor: PlatformActorContext | None) -> str | None:
    if actor is None:
        return None
    return actor.company_id


class CandidatePerformanceService:
    def get_overall(
        self,
        candidate_id: str,
        actor: PlatformActorContext | None = None,
    ) -> CandidateOverallPerformanceResponse:
        cid = (candidate_id or "").strip()
        if not cid:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail="candidate_id is required",
            )
        company_id = _actor_company(actor)
        self._enforce_tenant_visibility(cid, company_id)

        by_source = store.latest_ai_by_source_type(
            candidate_id=cid, company_id=company_id
        )
        mock = by_source.get("mock_interview")
        recruiter = by_source.get("recruiter_interview")
        latest_attempts = store.latest_assessment_attempts_by_id(
            candidate_id=cid, company_id=company_id
        )
        latest_assessment = latest_attempts[0] if latest_attempts else None

        mock_score = mock.overall_score if mock else None
        recruiter_score = recruiter.overall_score if recruiter else None
        # Platform ingest / combined scoring fill the recruiter bucket when no
        # dedicated recruiter_interview row exists.
        if recruiter_score is None:
            for key in ("candidate_scoring", "ingest"):
                row = by_source.get(key)
                if row is not None and row.overall_score is not None:
                    recruiter_score = row.overall_score
                    break
        assessment_score = latest_assessment.score if latest_assessment else None

        overall, breakdown = compute_overall_performance(
            mock_score=mock_score,
            recruiter_score=recruiter_score,
            assessment_score=assessment_score,
        )

        # Simpler blend preference: use latest AI overall for ai card
        latest_ai = store.latest_ai_evaluation(candidate_id=cid, company_id=company_id)
        ai_card = PerformanceScoreCard(
            score=latest_ai.overall_score if latest_ai else None,
            status="available" if latest_ai and latest_ai.overall_score is not None else "missing",
            available=bool(latest_ai and latest_ai.overall_score is not None),
            recorded_at=latest_ai.recorded_at if latest_ai else None,
        )
        assessment_card = PerformanceScoreCard(
            score=latest_assessment.score if latest_assessment else None,
            status=(
                latest_assessment.status
                if latest_assessment
                else "not_started"
            ),
            available=bool(latest_assessment),
            recorded_at=latest_assessment.recorded_at if latest_assessment else None,
        )
        timestamps = [
            t
            for t in [
                ai_card.recorded_at,
                assessment_card.recorded_at,
            ]
            if t is not None
        ]
        available = ai_card.available or assessment_card.available
        return CandidateOverallPerformanceResponse(
            candidate_id=cid,
            company_id=company_id,
            available=available,
            overall_score=overall,
            ai_performance=ai_card,
            assessment=assessment_card,
            breakdown=breakdown,
            updated_at=max(timestamps) if timestamps else None,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message=(
                "Candidate performance rollup"
                if available
                else "No stored performance results for this candidate"
            ),
        )

    def get_ai(
        self,
        candidate_id: str,
        actor: PlatformActorContext | None = None,
    ) -> CandidateAiPerformanceResponse:
        cid = (candidate_id or "").strip()
        if not cid:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail="candidate_id is required",
            )
        company_id = _actor_company(actor)
        self._enforce_tenant_visibility(cid, company_id)

        row = store.latest_ai_evaluation(candidate_id=cid, company_id=company_id)
        if row is None:
            return CandidateAiPerformanceResponse(
                candidate_id=cid,
                company_id=company_id,
                available=False,
                status=JobStatus.SUCCEEDED,
                stub=False,
                message="No stored AI performance for this candidate",
            )

        return CandidateAiPerformanceResponse(
            candidate_id=cid,
            company_id=company_id or (row.company_id or None) or None,
            available=True,
            evaluation_id=row.evaluation_id,
            interview_id=row.interview_id,
            source_type=row.source_type,
            role_title=row.role_title,
            score=row.overall_score,
            dimensions=AiDimensionScores(
                technical=row.technical_score,
                confidence=row.confidence_score,
                communication=row.communication_score,
                culture_fit=row.culture_fit_score,
            ),
            match_percent=row.match_percent,
            strengths=list(row.strengths or []),
            growth_areas=list(row.growth_areas or []),
            verified_skills=list(row.verified_skills or []),
            recommendation=HiringRecommendation(
                label=row.recommendation_label,
                display=row.recommendation_display,
                confidence=row.recommendation_confidence,
            ),
            recorded_at=row.recorded_at,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message="AI performance snapshot",
        )

    def get_assessments(
        self,
        candidate_id: str,
        actor: PlatformActorContext | None = None,
    ) -> CandidateAssessmentsPerformanceResponse:
        cid = (candidate_id or "").strip()
        if not cid:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail="candidate_id is required",
            )
        company_id = _actor_company(actor)
        self._enforce_tenant_visibility(cid, company_id)

        history_rows = store.list_assessment_attempts(
            candidate_id=cid, company_id=company_id
        )
        history = [
            AssessmentAttemptItem(
                attempt_id=r.attempt_id,
                assessment_id=r.assessment_id,
                attempt_number=r.attempt_number,
                kind=r.kind,
                role_title=r.role_title,
                score=r.score,
                status=r.status,
                passed=r.passed,
                skill_scores=list(r.skill_scores or []),
                recorded_at=r.recorded_at,
            )
            for r in history_rows
        ]
        latest_by_id = store.latest_assessment_attempts_by_id(
            candidate_id=cid, company_id=company_id
        )
        latest = history[0] if history else None
        scores = [r.score for r in latest_by_id if r.score is not None]
        summary: dict[str, Any] = {
            "attempt_count": len(history_rows),
            "distinct_assessments": len(latest_by_id),
            "latest_score": latest.score if latest else None,
            "best_score": max(scores) if scores else None,
            "retake_policy": "latest_attempt_per_assessment_id",
        }
        return CandidateAssessmentsPerformanceResponse(
            candidate_id=cid,
            company_id=company_id,
            available=bool(history),
            latest=latest,
            history=history,
            summary=summary,
            status=JobStatus.SUCCEEDED,
            stub=False,
            message=(
                "Assessment performance history"
                if history
                else "No stored assessment attempts for this candidate"
            ),
        )

    def ingest_ai(
        self,
        candidate_id: str,
        payload: AiPerformanceIngestRequest,
        actor: PlatformActorContext | None = None,
    ) -> CandidateAiPerformanceResponse:
        company_id = _actor_company(actor)
        source_key = (payload.source_key or "").strip()
        if not source_key:
            if payload.interview_id:
                source_key = f"interview:{payload.interview_id.strip()}"
            else:
                source_key = f"ingest:{uuid4().hex[:12]}"

        dims = map_interview_dimensions(
            overall_01=payload.overall_score,
            confidence_01=payload.confidence_score,
            communication_01=payload.communication_score,
            culture_fit_01=payload.culture_fit_score,
            category_scores=[
                {"key": "technical", "score": payload.technical_score},
            ]
            if payload.technical_score is not None
            else None,
        )
        # Prefer explicit dimension fields from payload over mapping defaults
        technical = clamp_score_100(payload.technical_score)
        if technical is None:
            technical = dims["technical_score"]
        confidence = clamp_score_100(payload.confidence_score)
        if confidence is None:
            confidence = dims["confidence_score"]
        communication = clamp_score_100(payload.communication_score)
        if communication is None:
            communication = dims["communication_score"]
        culture = clamp_score_100(payload.culture_fit_score)
        if culture is None:
            culture = dims["culture_fit_score"]
        overall = clamp_score_100(payload.overall_score)
        if overall is None:
            overall = dims["overall_score"]

        store.upsert_ai_evaluation(
            candidate_id=candidate_id,
            company_id=company_id,
            source_key=source_key,
            source_type=payload.source_type,
            interview_id=payload.interview_id,
            role_title=payload.role_title,
            overall_score=overall,
            technical_score=technical,
            confidence_score=confidence,
            communication_score=communication,
            culture_fit_score=culture,
            match_percent=payload.match_percent,
            recommendation_label=payload.recommendation_label,
            recommendation_confidence=payload.recommendation_confidence,
            strengths=payload.strengths,
            growth_areas=payload.growth_areas,
            verified_skills=payload.verified_skills,
            meta=payload.meta,
        )
        return self.get_ai(candidate_id, actor=actor)

    def ingest_assessment(
        self,
        candidate_id: str,
        payload: AssessmentAttemptIngestRequest,
        actor: PlatformActorContext | None = None,
    ) -> CandidateAssessmentsPerformanceResponse:
        company_id = _actor_company(actor)
        store.upsert_assessment_attempt(
            candidate_id=candidate_id,
            assessment_id=payload.assessment_id,
            company_id=company_id,
            attempt_number=payload.attempt_number,
            kind=payload.kind,
            role_title=payload.role_title,
            score=payload.score,
            max_score=payload.max_score,
            status=payload.status,
            passed=payload.passed,
            skill_scores=payload.skill_scores,
            feedback_markdown=payload.feedback_markdown,
            meta=payload.meta,
        )
        return self.get_assessments(candidate_id, actor=actor)

    def record_from_final_evaluation(
        self,
        *,
        candidate_id: str | None,
        company_id: str | None,
        interview_id: str,
        role_title: str,
        overall_01: float,
        category_scores: list[dict[str, Any]],
        strengths: list[str],
        growth_areas: list[str],
        verified_skills: list[str],
        hiring_fit_label: str | None,
        hiring_fit_score_01: float | None,
        source_type: str = "recruiter_interview",
        match_percent: float | None = None,
        meta: dict[str, Any] | None = None,
    ) -> None:
        """Best-effort persist after final-evaluation (never raises to caller)."""
        cid = (candidate_id or "").strip()
        if not cid:
            return
        try:
            dims = map_interview_dimensions(
                overall_01=overall_01,
                category_scores=category_scores,
            )
            store.upsert_ai_evaluation(
                candidate_id=cid,
                company_id=company_id,
                source_key=f"interview:{interview_id}",
                source_type=source_type,
                interview_id=interview_id,
                role_title=role_title,
                overall_score=dims["overall_score"],
                technical_score=dims["technical_score"],
                confidence_score=dims["confidence_score"],
                communication_score=dims["communication_score"],
                culture_fit_score=dims["culture_fit_score"],
                match_percent=match_percent,
                recommendation_label=hiring_fit_label,
                recommendation_confidence=hiring_fit_score_01,
                strengths=strengths,
                growth_areas=growth_areas,
                verified_skills=verified_skills,
                meta=meta or {},
            )
        except Exception:  # noqa: BLE001
            logger.exception(
                "failed to persist AI performance for candidate=%s interview=%s",
                cid,
                interview_id,
            )

    def record_from_assessment_grade(
        self,
        *,
        candidate_id: str | None,
        company_id: str | None,
        assessment_id: str,
        kind: str | None,
        role_title: str | None,
        total_score: float,
        max_total_score: float,
        passed: bool | None,
        skill_scores: list[dict[str, Any]] | None,
        feedback_markdown: str | None,
        attempt_number: int | None = None,
        meta: dict[str, Any] | None = None,
    ) -> str | None:
        """Persist attempt; returns attempt_id when saved."""
        cid = (candidate_id or "").strip()
        if not cid:
            return None
        try:
            row = store.upsert_assessment_attempt(
                candidate_id=cid,
                assessment_id=assessment_id,
                company_id=company_id,
                attempt_number=attempt_number,
                kind=kind,
                role_title=role_title,
                score=total_score,
                max_score=max_total_score if max_total_score else None,
                passed=passed,
                skill_scores=skill_scores,
                feedback_markdown=feedback_markdown,
                meta=meta or {},
            )
            return getattr(row, "attempt_id", None)
        except Exception:  # noqa: BLE001
            logger.exception(
                "failed to persist assessment attempt for candidate=%s assessment=%s",
                cid,
                assessment_id,
            )
            return None

    def _enforce_tenant_visibility(
        self,
        candidate_id: str,
        company_id: str | None,
    ) -> None:
        """Hide cross-tenant data: if caller sends X-Company-Id and only other
        tenants have rows, respond as not found / empty rather than leaking.
        """
        if not company_id:
            return
        owns = store.candidate_has_tenant_data(
            candidate_id=candidate_id, company_id=company_id
        )
        if owns:
            return
        if store.other_tenant_has_data(
            candidate_id=candidate_id, company_id=company_id
        ):
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Candidate performance not found for this tenant",
            )
