"""LEGACY live interview orchestrator — public /interviews/sessions/* removed.

Platform owns live sessions. This module is kept for possible re-enable but is
not wired to any HTTP route, so ``interview_sessions`` is not written via API.
Use ``POST /interviews/final-evaluation`` for scoring instead.
"""

from __future__ import annotations

import asyncio
import base64
import hashlib
import logging
import re
import secrets
from typing import Any, Awaitable, TypeVar
from uuid import uuid4

from app.config import get_settings
from app.errors import GatewayError
from app.prompts import Persona
from app.schemas.interview_session import (
    EvaluationSummary,
    InterviewSessionAnswerRequest,
    InterviewSessionAnswerResponse,
    InterviewSessionCompleteRequest,
    InterviewSessionCompleteResponse,
    InterviewSessionStartRequest,
    InterviewSessionStartResponse,
    InterviewSessionStateResponse,
    SessionPhase,
    SessionQuestionOut,
    SessionStatus,
)
from app.schemas.interviews import (
    EvaluateAnswerRequest,
    InterviewMode,
)
from app.services.face.audit_store import face_audit_store
from app.services.interviews import workflow_store
from app.services.interviews.session_store import (
    InterviewSession,
    SessionQuestion,
    session_store,
)
from app.services.interviews.core import InterviewsService
from app.services.voice import VoiceProviderError, get_stt_provider

logger = logging.getLogger(__name__)
T = TypeVar("T")


def _norm_text(text: str) -> str:
    return re.sub(r"\s+", " ", text.strip().lower())


def _answer_key(question_id: str, answer: str, idempotency_key: str | None) -> str:
    if idempotency_key:
        return f"idem:{idempotency_key}"
    digest = hashlib.sha256(answer.strip().encode("utf-8")).hexdigest()[:24]
    return f"{question_id}:{digest}"


def _to_out(q: SessionQuestion | None) -> SessionQuestionOut | None:
    if q is None:
        return None
    return SessionQuestionOut(
        id=q.id,
        text=q.text,
        kind=q.kind,
        parent_question_id=q.parent_question_id,
    )


def _remaining(session: InterviewSession) -> int:
    planned_ids = {q.id for q in session.planned_questions}
    return len(planned_ids - set(session.asked_question_ids))


def _eval_summary_from_dict(data: dict[str, Any]) -> EvaluationSummary:
    try:
        return EvaluationSummary.model_validate(data)
    except Exception:  # noqa: BLE001
        return EvaluationSummary(
            score=data.get("score"),
            feedback=data.get("feedback") or data.get("explanation"),
            strengths=list(data.get("strengths") or []),
            gaps=list(data.get("gaps") or data.get("weaknesses") or []),
            weaknesses=list(data.get("weaknesses") or data.get("gaps") or []),
            next_action=data.get("next_action"),
            degraded=True,
        )


async def _await_timeout(
    coro: Awaitable[T],
    *,
    seconds: float,
    label: str,
) -> T:
    try:
        return await asyncio.wait_for(coro, timeout=seconds)
    except asyncio.TimeoutError as exc:
        raise TimeoutError(f"{label} timed out after {seconds:.0f}s") from exc


class InterviewSessionService:
    def __init__(
        self,
        *,
        interviews: InterviewsService | None = None,
        store=session_store,
        ai_timeout_seconds: float | None = None,
    ) -> None:
        self._interviews = interviews or InterviewsService()
        self._store = store
        if ai_timeout_seconds is not None:
            self._ai_timeout = float(ai_timeout_seconds)
        else:
            try:
                self._ai_timeout = float(
                    getattr(get_settings(), "interview_ai_timeout_seconds", 45.0) or 45.0
                )
            except Exception:  # noqa: BLE001
                self._ai_timeout = 45.0

    def _load_planned_questions(
        self, payload: InterviewSessionStartRequest
    ) -> list[SessionQuestion]:
        """Resolve the Design preview bank — never generate new stems."""
        planned: list[SessionQuestion] = []
        for i, item in enumerate(payload.planned_questions or []):
            text = (item.text or "").strip()
            if not text:
                continue
            qid = (item.id or "").strip() or f"q-{i + 1}"
            if any(p.id == qid for p in planned):
                qid = f"q-{i + 1}-{uuid4().hex[:4]}"
            planned.append(SessionQuestion(id=qid, text=text, kind="planned"))

        if planned:
            return self._cap_planned(planned, payload.question_count)

        wid = (payload.workflow_id or "").strip() or None
        iid = (payload.interview_id or "").strip() or None
        row = None
        if wid:
            row = workflow_store.resolve_workflow(wid, company_id=None)
        if row is None and iid:
            row = workflow_store.get_workflow_by_interview_id(iid, company_id=None)
        if row is None:
            raise GatewayError(
                "No pre-authored questions found. Create an Interview Design "
                "workflow, generate/preview questions, then start the session "
                "with workflow_id or planned_questions.",
                code="questions_required",
                status_code=422,
            )
        qs = workflow_store.list_questions(row.workflow_id)
        for i, q in enumerate(qs):
            text = (q.text or "").strip()
            if not text:
                continue
            qid = (q.question_id or "").strip() or f"q-{i + 1}"
            if any(p.id == qid for p in planned):
                qid = f"q-{i + 1}"
            planned.append(SessionQuestion(id=qid, text=text, kind="planned"))
        if not planned:
            raise GatewayError(
                f"Workflow {row.workflow_id} has no questions. "
                "Generate questions in Interview Design before starting the live session.",
                code="questions_required",
                status_code=422,
            )
        return self._cap_planned(planned, payload.question_count)

    @staticmethod
    def _cap_planned(
        planned: list[SessionQuestion], question_count: int | None
    ) -> list[SessionQuestion]:
        if question_count is None or question_count <= 0:
            return planned
        return planned[: int(question_count)]

    def _checkpoint(self, session: InterviewSession) -> None:
        try:
            self._store.save(session)
        except Exception as exc:  # noqa: BLE001
            logger.warning("checkpoint failed for %s: %s", session.interview_id, exc)

    def _require_session(
        self, interview_id: str, *, allow_recover: bool = True
    ) -> tuple[InterviewSession, bool]:
        session, recovered = self._store.get(interview_id, allow_recover=allow_recover)
        if session is None:
            raise GatewayError(
                f"Interview session not found: {interview_id}",
                code="session_not_found",
                status_code=404,
            )
        return session, recovered

    async def start(
        self, payload: InterviewSessionStartRequest
    ) -> InterviewSessionStartResponse:
        interview_id = payload.interview_id or f"int-{uuid4().hex[:12]}"
        existing, _ = self._store.get(interview_id, allow_recover=True)
        if existing is not None:
            raise GatewayError(
                f"Interview session already exists: {interview_id}",
                code="session_exists",
                status_code=409,
            )

        settings = get_settings()
        require_face = (
            payload.require_face_verification
            if payload.require_face_verification is not None
            else bool(settings.face_verification_required_for_session)
        )
        face_audit = None
        if require_face:
            face_audit = face_audit_store.latest_passed(
                interview_id,
                max_age_seconds=float(settings.face_verification_ttl_seconds),
            )
            if face_audit is None:
                raise GatewayError(
                    "Face verification required before starting this interview. "
                    "Complete POST /face-verification/enroll at registration, then "
                    "POST /face-verification/verify with the same interview_id and "
                    "user_id (live frames) until verified=true.",
                    code="face_verification_required",
                    status_code=403,
                )

        warnings: list[str] = []
        degraded = False
        planned = self._load_planned_questions(payload)

        access_token = secrets.token_urlsafe(32)
        owner_id = (payload.owner_id or "").strip() or None
        session = InterviewSession(
            interview_id=interview_id,
            role_title=payload.role_title,
            job_description=payload.job_description,
            persona=payload.persona.value,
            language=payload.language,
            skills_focus=list(payload.skills),
            planned_questions=planned,
            max_follow_ups_per_question=0,  # no live adaptive question generation
            follow_up_score_threshold=payload.follow_up_score_threshold,
            face_verified=bool(face_audit is not None),
            face_audit_id=face_audit.audit_id if face_audit else None,
            face_verified_at=face_audit.created_at if face_audit else None,
            access_token=access_token,
            owner_id=owner_id,
        )

        current = self._local_next_planned(session)

        if current is None:
            session.status = SessionStatus.COMPLETED.value
            session.phase = SessionPhase.COMPLETED.value
        else:
            session.current_question = current
            session.phase = SessionPhase.AWAITING_ANSWER.value
            session.status = SessionStatus.ACTIVE.value

        try:
            self._store.create(session)
        except KeyError as exc:
            raise GatewayError(
                f"Interview session already exists: {interview_id}",
                code="session_exists",
                status_code=409,
            ) from exc

        return InterviewSessionStartResponse(
            correlation_id=payload.correlation_id,
            interview_id=interview_id,
            session_access_token=access_token,
            owner_id=owner_id,
            session_status=SessionStatus(session.status),
            phase=SessionPhase(session.phase),
            role_title=session.role_title,
            persona=Persona(session.persona),
            planned_question_ids=[q.id for q in session.planned_questions],
            current_question=_to_out(session.current_question),
            questions_remaining=_remaining(session),
            face_verified=session.face_verified,
            face_audit_id=session.face_audit_id,
            stub=degraded,
            message="Interview session started",
            degraded=degraded,
            warnings=warnings,
            checkpoint_version=session.checkpoint_version,
        )

    async def answer(
        self, interview_id: str, payload: InterviewSessionAnswerRequest
    ) -> InterviewSessionAnswerResponse:
        session, recovered = self._require_session(interview_id)
        warnings: list[str] = []
        if recovered:
            warnings.append("Session recovered from durable checkpoint")

        with session.lock:
            if session.status == SessionStatus.COMPLETED.value:
                raise GatewayError(
                    "Interview session already completed",
                    code="session_completed",
                    status_code=409,
                )

            degraded = recovered
            stt_provider: str | None = None
            answer_text = (payload.answer or "").strip()

            if payload.audio_base64 and payload.audio_base64.strip():
                try:
                    audio_bytes = base64.b64decode(payload.audio_base64, validate=False)
                except Exception as exc:  # noqa: BLE001
                    raise GatewayError(
                        "Invalid audio_base64",
                        code="invalid_audio",
                        status_code=400,
                    ) from exc
                try:
                    stt = get_stt_provider()
                    stt_result = await _await_timeout(
                        stt.transcribe(
                            audio_bytes=audio_bytes,
                            language=payload.language or session.language,
                            mime_type=payload.audio_mime_type or "audio/wav",
                            options=payload.options,
                        ),
                        seconds=self._ai_timeout,
                        label="transcription/STT",
                    )
                    stt_provider = stt_result.provider
                    answer_text = (stt_result.text or "").strip()
                    if stt_result.stub:
                        degraded = True
                        warnings.append(stt_result.message)
                except VoiceProviderError as exc:
                    raise GatewayError(
                        str(exc),
                        code=exc.code,
                        status_code=400,
                    ) from exc
                except TimeoutError as exc:
                    raise GatewayError(
                        str(exc),
                        code="stt_timeout",
                        status_code=504,
                    ) from exc

            if not answer_text:
                raise GatewayError(
                    "Empty transcript / answer after STT",
                    code="empty_transcript",
                    status_code=400,
                )

            current = session.current_question
            question_id = (payload.question_id or "").strip()
            # Swagger Try-it-out bakes sample ids (q-cache-design-001 / "string")
            # that never match the live session question from sessions/start.
            _swagger_qids = {
                "string",
                "question_id",
                "q-cache-design-001",
                "q1",
                "cq1",
            }
            if (
                current is not None
                and (
                    not question_id
                    or question_id in _swagger_qids
                    or question_id.startswith(":")
                    or question_id.startswith("<")
                )
            ):
                question_id = current.id

            key = _answer_key(
                question_id, answer_text, payload.idempotency_key
            )
            if key in session.processed_answer_keys:
                return InterviewSessionAnswerResponse(
                    correlation_id=payload.correlation_id,
                    interview_id=interview_id,
                    session_status=SessionStatus(session.status),
                    phase=SessionPhase(session.phase),
                    duplicate=True,
                    evaluation=(
                        _eval_summary_from_dict(session.evaluations[-1])
                        if session.evaluations
                        else None
                    ),
                    current_question=_to_out(session.current_question),
                    questions_remaining=_remaining(session),
                    completed=session.status == SessionStatus.COMPLETED.value,
                    asked_question_ids=list(session.asked_question_ids),
                    transcript_text=answer_text,
                    stt_provider=stt_provider,
                    stub=True,
                    message="Duplicate answer ignored",
                    degraded=False,
                    warnings=["Duplicate answer/follow-up processing skipped"],
                    recovered=recovered,
                    checkpoint_version=session.checkpoint_version,
                )

            if current is None or current.id != question_id:
                raise GatewayError(
                    "Answer does not match the current question",
                    code="question_mismatch",
                    status_code=409,
                    details={
                        "expected_question_id": current.id if current else None,
                        "received_question_id": question_id or None,
                    },
                )

            # Persist progress BEFORE AI calls so timeouts/crashes don't lose the turn
            session.asked_question_ids.append(current.id)
            session.asked_question_texts_norm.add(_norm_text(current.text))
            session.transcript.append(
                {
                    "turn_id": f"t-{session.turn_count + 1}-q",
                    "role": "interviewer",
                    "text": current.text,
                }
            )
            session.transcript.append(
                {
                    "turn_id": f"t-{session.turn_count + 1}-a",
                    "role": "candidate",
                    "text": answer_text,
                    "via": "stt" if stt_provider else "text",
                    "stt_provider": stt_provider,
                }
            )
            session.turn_count += 1
            session.processed_answer_keys.add(key)
            self._checkpoint(session)

            evaluation, eval_degraded, eval_warnings = await self._evaluate(
                session, current, answer_text, payload.correlation_id
            )
            degraded = degraded or eval_degraded
            warnings.extend(eval_warnings)
            session.last_score = evaluation.score
            session.evaluations.append(evaluation.model_dump())
            self._checkpoint(session)

            # Advance through the pre-authored Design bank only (no live generation).
            next_q = self._local_next_planned(session)

            if next_q is None:
                session.current_question = None
                session.status = SessionStatus.COMPLETED.value
                session.phase = SessionPhase.COMPLETED.value
                completed = True
            else:
                session.current_question = next_q
                session.status = SessionStatus.ACTIVE.value
                session.phase = SessionPhase.AWAITING_ANSWER.value
                completed = False

            self._checkpoint(session)

            return InterviewSessionAnswerResponse(
                correlation_id=payload.correlation_id,
                interview_id=interview_id,
                session_status=SessionStatus(session.status),
                phase=SessionPhase(session.phase),
                duplicate=False,
                evaluation=evaluation,
                current_question=_to_out(session.current_question),
                questions_remaining=_remaining(session),
                asked_question_ids=list(session.asked_question_ids),
                completed=completed,
                transcript_text=answer_text,
                stt_provider=stt_provider,
                stub=degraded,
                message=(
                    "Interview completed"
                    if completed
                    else "Answer processed; next prompt ready"
                ),
                degraded=degraded,
                warnings=warnings,
                recovered=recovered,
                checkpoint_version=session.checkpoint_version,
            )

    def get_state(
        self, interview_id: str, correlation_id=None
    ) -> InterviewSessionStateResponse:
        session, recovered = self._require_session(interview_id)
        return InterviewSessionStateResponse(
            correlation_id=correlation_id,
            interview_id=interview_id,
            session_status=SessionStatus(session.status),
            phase=SessionPhase(session.phase),
            role_title=session.role_title,
            persona=Persona(session.persona),
            planned_question_ids=[q.id for q in session.planned_questions],
            asked_question_ids=list(session.asked_question_ids),
            current_question=_to_out(session.current_question),
            questions_remaining=_remaining(session),
            last_score=session.last_score,
            turn_count=session.turn_count,
            transcript=list(session.transcript),
            stub=False,
            message="Recovered from checkpoint" if recovered else "OK",
            recovered=recovered,
            checkpoint_version=session.checkpoint_version,
            evaluations=list(session.evaluations),
        )

    def recover(
        self, interview_id: str, correlation_id=None
    ) -> InterviewSessionStateResponse:
        """Explicit recovery from durable checkpoint (evicts stale memory first)."""
        self._store.evict(interview_id)
        session, recovered = self._require_session(interview_id, allow_recover=True)
        return InterviewSessionStateResponse(
            correlation_id=correlation_id,
            interview_id=interview_id,
            session_status=SessionStatus(session.status),
            phase=SessionPhase(session.phase),
            role_title=session.role_title,
            persona=Persona(session.persona),
            planned_question_ids=[q.id for q in session.planned_questions],
            asked_question_ids=list(session.asked_question_ids),
            current_question=_to_out(session.current_question),
            questions_remaining=_remaining(session),
            last_score=session.last_score,
            turn_count=session.turn_count,
            transcript=list(session.transcript),
            stub=False,
            message=(
                "Session recovered from durable checkpoint"
                if recovered
                else "Session loaded"
            ),
            recovered=recovered or True,
            checkpoint_version=session.checkpoint_version,
            evaluations=list(session.evaluations),
        )

    def complete(
        self,
        interview_id: str,
        payload: InterviewSessionCompleteRequest | None = None,
    ) -> InterviewSessionCompleteResponse:
        session, recovered = self._require_session(interview_id)
        with session.lock:
            session.status = SessionStatus.COMPLETED.value
            session.phase = SessionPhase.COMPLETED.value
            session.current_question = None
            self._checkpoint(session)
            reason = (payload.reason if payload else None) or "client_complete"
            return InterviewSessionCompleteResponse(
                correlation_id=payload.correlation_id if payload else None,
                interview_id=interview_id,
                session_status=SessionStatus.COMPLETED,
                phase=SessionPhase.COMPLETED,
                asked_question_ids=list(session.asked_question_ids),
                turn_count=session.turn_count,
                last_score=session.last_score,
                stub=False,
                message=f"Interview completed ({reason})",
                recovered=recovered,
                checkpoint_version=session.checkpoint_version,
            )

    async def _evaluate(
        self,
        session: InterviewSession,
        question: SessionQuestion,
        answer: str,
        correlation_id,
    ) -> tuple[EvaluationSummary, bool, list[str]]:
        try:
            res = await _await_timeout(
                self._interviews.evaluate_answer(
                    EvaluateAnswerRequest(
                        correlation_id=correlation_id,
                        interview_id=session.interview_id,
                        interview_mode=InterviewMode.TEXT,
                        persona=Persona(session.persona),
                        role_title=session.role_title,
                        job_description=session.job_description,
                        question=question.text,
                        candidate_answer=answer,
                        skills_focus=session.skills_focus,
                        language=session.language,
                    )
                ),
                seconds=self._ai_timeout,
                label="evaluate-answer",
            )
            # Invalid / empty model payload → heuristic
            if res is None or (res.score is None and not res.dimensions):
                raise ValueError("invalid evaluate-answer response")
            weaknesses = list(res.weaknesses or res.gaps)
            return (
                EvaluationSummary(
                    score=res.score,
                    score_band=res.score_band.value if res.score_band else None,
                    explanation=res.explanation or res.feedback,
                    feedback=res.feedback or res.explanation,
                    strengths=list(res.strengths),
                    weaknesses=weaknesses,
                    gaps=weaknesses,
                    improvement_feedback=list(res.improvement_feedback),
                    next_action=res.next_action,
                    degraded=bool(res.stub),
                    calibrated=bool(res.calibrated),
                    partial_credit=bool(res.partial_credit),
                    dimensions=[d.model_dump() for d in res.dimensions],
                ),
                bool(res.stub),
                ([f"Evaluate used fallback: {res.message}"] if res.stub else []),
            )
        except Exception as exc:  # noqa: BLE001
            logger.warning("evaluate-answer failed: %s", exc)
            length = len(answer.strip())
            score = 0.45 if length < 40 else 0.7 if length < 200 else 0.85
            return (
                EvaluationSummary(
                    score=score,
                    score_band=(
                        "needs_improvement" if score < 0.6 else "good"
                    ),
                    explanation="Evaluation unavailable; continued with heuristic score.",
                    feedback="Evaluation unavailable; continued with heuristic score.",
                    strengths=[],
                    gaps=["Evaluator unavailable"],
                    weaknesses=["Evaluator unavailable"],
                    improvement_feedback=["Retry with a fuller answer if possible"],
                    next_action="continue",
                    degraded=True,
                ),
                True,
                [f"evaluate-answer failed; heuristic used: {exc}"],
            )

    def _local_next_planned(self, session: InterviewSession) -> SessionQuestion | None:
        for q in session.planned_questions:
            if q.id in session.asked_question_ids:
                continue
            if _norm_text(q.text) in session.asked_question_texts_norm:
                continue
            return q
        return None
