"""Interview creation workflow — setup is source of truth; no resend of full config."""

from __future__ import annotations

import logging
from typing import Any

from fastapi import HTTPException, status

from app.deps import PlatformActorContext
from app.path_ids import blank_if_placeholder, is_placeholder_id
from app.prompts import DEFAULT_PERSONA_CATALOG, PERSONA_DESCRIPTIONS, Persona
from app.schemas.interview_workflows import (
    InterviewWorkflowCreateRequest,
    InterviewWorkflowPatchRequest,
    InterviewWorkflowResponse,
    WorkflowQuestionCreateRequest,
    WorkflowQuestionGenerateRequest,
    WorkflowQuestionOut,
    WorkflowQuestionPatchRequest,
    WorkflowQuestionsBatchRequest,
)
from app.schemas.questions import Difficulty, QuestionType, RoleQuestionGenRequest
from app.services.interviews import workflow_store as store
from app.services.screening.questions import QuestionsService

logger = logging.getLogger(__name__)

_PERSONA_ALIASES: dict[str, Persona] = {
    "technical": Persona.TECHNICAL,
    "technical_interviewer": Persona.TECHNICAL,
    "professional_interviewer": Persona.TECHNICAL,
    "hr_behavioral": Persona.HR_BEHAVIORAL,
    "hr": Persona.HR_BEHAVIORAL,
    "behavioral": Persona.HR_BEHAVIORAL,
    "friendly_coach": Persona.FRIENDLY_COACH,
    "coach": Persona.FRIENDLY_COACH,
    "executive": Persona.EXECUTIVE,
    "executive_leadership_panel": Persona.EXECUTIVE,
    "sales": Persona.SALES,
    "healthcare": Persona.HEALTHCARE,
    "finance": Persona.FINANCE,
    "custom": Persona.CUSTOM,
}

_TYPE_ALIASES: dict[str, QuestionType] = {
    "technical": QuestionType.SHORT_ANSWER,
    "scenario": QuestionType.LONG_ANSWER,
    "behavioral": QuestionType.SHORT_ANSWER,
    "mcq": QuestionType.MCQ,
    "short_answer": QuestionType.SHORT_ANSWER,
    "long_answer": QuestionType.LONG_ANSWER,
    "coding": QuestionType.CODING,
    "true_false": QuestionType.TRUE_FALSE,
}

_VALID_MODES = frozenset({"text", "voice", "video"})

_DEFAULT_CRITERIA: dict[str, list[str]] = {
    "technical": ["technical_depth", "clarity", "tradeoff_reasoning"],
    "scenario": ["problem_framing", "decision_quality", "ownership"],
    "behavioral": ["star_structure", "impact", "self_awareness"],
    "short_answer": ["relevance", "clarity", "evidence"],
    "long_answer": ["structure", "depth", "examples"],
    "mcq": ["accuracy"],
    "coding": ["correctness", "complexity", "edge_cases"],
    "true_false": ["accuracy"],
}

_CATEGORY_FOR_TYPE: dict[str, str] = {
    "technical": "Technical",
    "scenario": "Scenario",
    "behavioral": "Behavioral",
    "short_answer": "Technical",
    "long_answer": "Scenario",
    "mcq": "Knowledge",
    "coding": "Coding",
    "true_false": "Knowledge",
}


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


def _actor_user(actor: PlatformActorContext | None) -> str | None:
    return actor.user_id if actor else None


def _resolve_persona(persona_id: str | None) -> Persona:
    """Map catalog aliases / enum values; unknown ids (e.g. custom UUID) → CUSTOM."""
    cleaned = blank_if_placeholder(persona_id)
    if not cleaned:
        return Persona.TECHNICAL
    key = cleaned.strip().lower().replace("-", "_").replace(" ", "_")
    if key in _PERSONA_ALIASES:
        return _PERSONA_ALIASES[key]
    try:
        return Persona(key)
    except ValueError:
        # Custom persona_id from POST /personas (UUID) or free-form company id
        return Persona.CUSTOM


def _persona_instruction_block(persona_id: str, persona: Persona) -> str:
    """Prefer saved custom persona config; fall back to built-in catalog text."""
    try:
        from app.services.personas.store import get_by_id

        row = get_by_id(persona_id)
    except Exception:  # noqa: BLE001
        row = None
    if row is not None:
        criteria = ", ".join(row.evaluation_criteria or []) or "role fit"
        recommended = ", ".join(row.recommended_for or []) or "general roles"
        prompt = (row.system_prompt or "").strip()
        style = (row.style_summary or "").strip()
        parts = [
            f"Persona id={row.persona_id}; name={row.name}; custom company persona.",
            f"Description: {row.description}",
            f"Tone: {row.tone}. Depth: {row.depth}. Style: {row.interview_style}.",
            f"Recommended for: {recommended}. Weigh: {criteria}.",
        ]
        if style:
            parts.append(f"Style summary: {style}")
        if prompt:
            parts.append(f"System prompt guidance: {prompt}")
        parts.append(
            "Generate questions that match this interviewer's tone, depth, and style."
        )
        return " ".join(parts)

    meta = DEFAULT_PERSONA_CATALOG.get(persona)
    if meta:
        recommended = ", ".join(meta.get("recommended_for") or []) or "general roles"  # type: ignore[arg-type]
        criteria = ", ".join(meta.get("evaluation_criteria") or []) or "role fit"  # type: ignore[arg-type]
        return (
            f"Persona id={persona_id}; name={meta['name']}; built-in persona={persona.value}. "
            f"Description: {meta['description']} "
            f"Tone: {meta['tone']}. Depth: {meta['depth']}. "
            f"Style: {meta.get('interview_style', '')}. "
            f"Recommended for: {recommended}. Weigh: {criteria}. "
            "Generate questions that match this interviewer's tone, depth, and style."
        )
    desc = PERSONA_DESCRIPTIONS.get(persona, "")
    return (
        f"Persona id={persona_id}; persona={persona.value}. "
        f"Persona focus: {desc} "
        "Generate questions that match this interviewer's tone, depth, and style."
    )


def _resolve_difficulty(raw: str | None) -> Difficulty:
    key = (raw or "medium").strip().lower()
    aliases = {
        "easy": Difficulty.EASY,
        "medium": Difficulty.MEDIUM,
        "hard": Difficulty.HARD,
        "mid": Difficulty.MEDIUM,
        "mid-level": Difficulty.MEDIUM,
        "mid_level": Difficulty.MEDIUM,
        "intermediate": Difficulty.MEDIUM,
    }
    return aliases.get(key, Difficulty.MEDIUM)


def _map_question_types(raw: list[str] | None) -> list[QuestionType]:
    out: list[QuestionType] = []
    for item in raw or []:
        key = str(item).strip().lower().replace("-", "_")
        if is_placeholder_id(key):
            continue
        qt = _TYPE_ALIASES.get(key)
        if qt and qt not in out:
            out.append(qt)
    return out or [QuestionType.SHORT_ANSWER]


def _coerce_mode(
    raw: str | None, *, default: str = "video", strict: bool = True
) -> str:
    """Normalize Design mode to text|voice|video. Blank → default; invalid → 422 when strict."""
    from fastapi import HTTPException, status

    if raw is None:
        return default
    if hasattr(raw, "value"):
        raw = getattr(raw, "value")
    cleaned = blank_if_placeholder(str(raw) if raw is not None else None)
    if not cleaned:
        return default
    key = cleaned.strip().lower()
    if key in _VALID_MODES:
        return key
    if not strict:
        return default
    raise HTTPException(
        status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
        detail=f"mode must be one of: text, voice, video (got {cleaned!r})",
    )


def _sanitize_experience(raw: str | None) -> str | None:
    return blank_if_placeholder(raw)


def _sanitize_interview_id(raw: str | None) -> str | None:
    return blank_if_placeholder(raw)


def _default_response_seconds(
    duration_minutes: int | None, question_count: int
) -> int:
    minutes = duration_minutes or 30
    count = max(question_count, 1)
    # Leave ~20% buffer for intro/outro; clamp 60–600s
    per = int((minutes * 60 * 0.8) / count)
    return max(60, min(600, per))


def _default_criteria(question_type: str | None) -> list[str]:
    key = (question_type or "short_answer").strip().lower().replace("-", "_")
    return list(_DEFAULT_CRITERIA.get(key) or _DEFAULT_CRITERIA["short_answer"])


def _default_category(question_type: str | None) -> str:
    key = (question_type or "short_answer").strip().lower().replace("-", "_")
    return _CATEGORY_FOR_TYPE.get(key, "Technical")


def _synthesize_jd(
    role: str, skills: list[str], experience: str | None, title: str
) -> str:
    skills_txt = ", ".join(skills) if skills else "role-relevant skills"
    exp = experience or "relevant"
    return (
        f"Role: {role or title}. Experience level: {exp}. "
        f"Required skills: {skills_txt}. "
        "Conduct a structured interview assessing depth, ownership, "
        "and applied competence for this role."
    )


def _question_out(
    row,
    *,
    locked: bool = False,
    default_response_seconds: int | None = None,
) -> WorkflowQuestionOut:
    meta = dict(row.meta or {})
    criteria = list(row.evaluation_criteria or [])
    if not criteria:
        criteria = _default_criteria(row.question_type)
    category = row.category or _default_category(row.question_type)
    response_secs = row.response_time_seconds
    if response_secs is None and default_response_seconds is not None:
        response_secs = default_response_seconds
    explanation = meta.get("explanation")
    answer = meta.get("answer")
    options = list(meta.get("options") or [])
    return WorkflowQuestionOut(
        questionId=row.question_id,
        id=row.question_id,
        text=row.text,
        stem=row.text,
        questionType=row.question_type,
        skill=row.skill,
        difficulty=row.difficulty,
        category=category,
        evaluationCriteria=criteria,
        source=row.source,
        position=row.position,
        responseFormat=row.response_format or "text",
        responseTimeSeconds=response_secs,
        options=options,
        explanation=explanation,
        answer=answer if isinstance(answer, str) or answer is None else str(answer),
        locked=locked,
        createdAt=row.created_at,
        updatedAt=row.updated_at,
    )


def _workflow_response(row, questions=None) -> InterviewWorkflowResponse:
    qs = questions if questions is not None else store.list_questions(row.workflow_id)
    per_q = _default_response_seconds(row.duration_minutes, len(qs) or 1)
    # Note: `status` here is workflow lifecycle (draft/…/ready), not JobStatus.
    return InterviewWorkflowResponse(
        stub=False,
        message="OK",
        workflowId=row.workflow_id,
        interviewId=row.interview_id,
        companyId=row.company_id or None,
        userId=row.user_id,
        title=row.title,
        roleTitle=row.role_title,
        skills=list(row.skills or []),
        experienceLevel=row.experience_level,
        durationMinutes=row.duration_minutes,
        language=row.language,
        difficulty=row.difficulty,
        mode=row.mode,
        personaId=row.persona_id,
        jobDescription=row.job_description,
        status=row.status,
        version=row.version,
        questions=[_question_out(q, default_response_seconds=per_q) for q in qs],
        questionCount=len(qs),
        createdAt=row.created_at,
        updatedAt=row.updated_at,
    )


class InterviewWorkflowService:
    def __init__(self) -> None:
        self._questions = QuestionsService()

    def _get_or_404(
        self, workflow_id: str, actor: PlatformActorContext | None
    ):
        company = _actor_company(actor)
        row = store.resolve_workflow(workflow_id, company_id=company)
        if row is None:
            # Tenant isolation: hide other-tenant rows
            bare = store.resolve_workflow(workflow_id, company_id=None)
            if bare is not None and company:
                raise HTTPException(
                    status_code=status.HTTP_404_NOT_FOUND,
                    detail="Interview workflow not found for this tenant",
                )
            raise HTTPException(
                status_code=status.HTTP_404_NOT_FOUND,
                detail="Interview workflow not found",
            )
        return row

    def create(
        self,
        payload: InterviewWorkflowCreateRequest,
        actor: PlatformActorContext | None = None,
    ) -> InterviewWorkflowResponse:
        role = payload.resolved_role_title()
        if not role or is_placeholder_id(role):
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail="role / roleTitle is required",
            )
        experience = _sanitize_experience(payload.experience_level)
        interview_id = _sanitize_interview_id(payload.interview_id)
        mode = _coerce_mode(
            payload.mode.value if hasattr(payload.mode, "value") else payload.mode
        )
        jd = (payload.job_description or "").strip()
        if len(jd) < 20 or is_placeholder_id(jd):
            jd = _synthesize_jd(role, payload.skills, experience, payload.title)

        title = payload.title.strip()
        if is_placeholder_id(title):
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail="title is required",
            )

        row = store.create_workflow(
            title=title,
            role_title=role,
            company_id=_actor_company(actor),
            user_id=_actor_user(actor),
            interview_id=interview_id,
            skills=[s for s in payload.skills if not is_placeholder_id(s)],
            experience_level=experience,
            duration_minutes=payload.duration_minutes,
            language=blank_if_placeholder(payload.language) or "en",
            difficulty=(payload.difficulty or "medium").lower(),
            mode=mode,
            job_description=jd,
            meta=dict(payload.options or {}),
        )
        resp = _workflow_response(row, questions=[])
        resp.message = "Interview workflow draft created"
        return resp

    def get(
        self, workflow_id: str, actor: PlatformActorContext | None = None
    ) -> InterviewWorkflowResponse:
        return _workflow_response(self._get_or_404(workflow_id, actor))

    def patch(
        self,
        workflow_id: str,
        payload: InterviewWorkflowPatchRequest,
        actor: PlatformActorContext | None = None,
    ) -> InterviewWorkflowResponse:
        existing = self._get_or_404(workflow_id, actor)
        wid = existing.workflow_id
        fields: dict[str, Any] = {}
        if payload.title is not None:
            title = payload.title.strip()
            if not is_placeholder_id(title):
                fields["title"] = title
        role = (payload.role_title or payload.role or "").strip()
        if role and not is_placeholder_id(role):
            fields["role_title"] = role
        if payload.skills is not None:
            fields["skills"] = [s for s in payload.skills if not is_placeholder_id(s)]
        if payload.experience_level is not None:
            fields["experience_level"] = _sanitize_experience(payload.experience_level)
        if payload.duration_minutes is not None:
            fields["duration_minutes"] = payload.duration_minutes
        if payload.language is not None:
            lang = blank_if_placeholder(payload.language)
            if lang:
                fields["language"] = lang
        if payload.difficulty is not None:
            fields["difficulty"] = payload.difficulty.lower()
        if payload.mode is not None:
            fields["mode"] = _coerce_mode(
                payload.mode.value if hasattr(payload.mode, "value") else payload.mode
            )
        if payload.job_description is not None:
            jd = payload.job_description.strip()
            if jd and not is_placeholder_id(jd):
                fields["job_description"] = jd
        if payload.interview_id is not None:
            cleaned_iid = _sanitize_interview_id(payload.interview_id)
            # Ignore Swagger placeholders; do not wipe a real interviewId.
            if cleaned_iid is not None:
                fields["interview_id"] = cleaned_iid
        if payload.options is not None:
            fields["meta"] = payload.options
        if payload.persona_id is not None:
            persona = blank_if_placeholder(payload.persona_id)
            if persona:
                fields["persona_id"] = persona.strip()
                fields["status"] = "persona_selected"

        row = store.update_workflow(
            wid, company_id=_actor_company(actor), fields=fields
        )
        if row is None:
            raise HTTPException(status_code=404, detail="Interview workflow not found")
        resp = _workflow_response(row)
        resp.message = "Interview workflow updated"
        return resp

    async def generate_questions(
        self,
        workflow_id: str,
        payload: WorkflowQuestionGenerateRequest,
        actor: PlatformActorContext | None = None,
    ) -> InterviewWorkflowResponse:
        row = self._get_or_404(workflow_id, actor)
        wid = row.workflow_id

        persona_raw = blank_if_placeholder(payload.persona_id)
        if not persona_raw:
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail="personaId is required for question generation",
            )
        persona_id = persona_raw.strip()
        persona = _resolve_persona(persona_id)

        # Persist persona on workflow before generating
        store.update_workflow(
            wid,
            company_id=_actor_company(actor),
            fields={"persona_id": persona_id, "status": "persona_selected"},
        )
        row = self._get_or_404(wid, actor)

        jd = (row.job_description or "").strip()
        if len(jd) < 20:
            jd = _synthesize_jd(
                row.role_title, list(row.skills or []), row.experience_level, row.title
            )

        gen_req = RoleQuestionGenRequest(
            correlation_id=payload.correlation_id,
            role_title=row.role_title,
            job_description=jd,
            persona=persona,
            seniority=row.experience_level,
            skills=list(row.skills or []),
            candidate_id=payload.candidate_id,
            company_id=row.company_id or None,
            resume_text=payload.resume_text,
            resume_structured=dict(payload.resume_structured or {}),
            content_base64=payload.content_base64,
            source_url=payload.source_url,
            document_type=payload.document_type,
            filename=payload.filename,
            question_types=_map_question_types(payload.question_types),
            difficulty=_resolve_difficulty(row.difficulty),
            count=payload.question_count,
            language=(row.language or "en")[:10],
            instructions=(
                f"Interview mode={row.mode}; duration={row.duration_minutes} minutes. "
                f"{_persona_instruction_block(persona_id, persona)}"
            ),
        )
        generated = await self._questions.generate_from_role(gen_req)
        per_q = _default_response_seconds(row.duration_minutes, payload.question_count)
        items: list[dict[str, Any]] = []
        for q in generated.questions:
            qtype = (
                q.question_type.value
                if hasattr(q.question_type, "value")
                else str(q.question_type)
            )
            meta_cat = (q.metadata or {}).get("category")
            meta_crit = list((q.metadata or {}).get("evaluation_criteria") or [])
            items.append(
                {
                    "question_id": q.id,
                    "text": q.stem,
                    "question_type": qtype,
                    "difficulty": q.difficulty.value
                    if hasattr(q.difficulty, "value")
                    else str(q.difficulty),
                    "skill": (q.metadata or {}).get("skill")
                    or (list(row.skills or [])[:1] or [None])[0],
                    "category": meta_cat or _default_category(qtype),
                    "evaluation_criteria": meta_crit or _default_criteria(qtype),
                    "response_format": "text",
                    "response_time_seconds": per_q,
                    "meta": {
                        "explanation": q.explanation,
                        "answer": q.answer,
                        "options": [o.model_dump() for o in (q.options or [])],
                        "stub": generated.stub,
                        "stem": q.stem,
                        "persona_id": persona_id,
                        "persona": persona.value,
                    },
                }
            )

        # replace_existing=True → drop prior AI questions, keep custom.
        qs = store.replace_ai_questions(
            wid,
            items,
            keep_custom=True,
        )

        # Completing design workflow (preview removed): ready when we have questions
        final_status = (
            "ready_for_scheduling" if qs else "questions_ready"
        )
        updated = store.update_workflow(
            wid,
            company_id=_actor_company(actor),
            fields={
                "status": final_status,
                "persona_id": persona_id,
            },
        )
        resp = _workflow_response(updated or row, questions=qs)
        resp.stub = bool(generated.stub)
        resp.message = (
            f"Generated {len(items)} questions for persona `{persona_id}` "
            f"({persona.value}) via {generated.message or 'questions service'}; "
            f"workflow status={final_status}"
        )
        return resp

    def _create_item_dict(
        self,
        payload: WorkflowQuestionCreateRequest,
        *,
        duration_minutes: int | None,
    ) -> dict[str, Any]:
        return {
            "text": payload.text,
            "question_type": payload.question_type,
            "skill": payload.skill,
            "difficulty": payload.difficulty,
            "category": payload.category or _default_category(payload.question_type),
            "evaluation_criteria": payload.evaluation_criteria
            or _default_criteria(payload.question_type),
            "source": "custom",
            "response_format": payload.response_format,
            "response_time_seconds": payload.response_time_seconds
            or _default_response_seconds(duration_minutes, 1),
            "position": payload.position,
            "meta": payload.meta,
        }

    @staticmethod
    def _patch_fields(payload: WorkflowQuestionPatchRequest) -> dict[str, Any]:
        mapping = {
            "text": payload.text,
            "question_type": payload.question_type,
            "skill": payload.skill,
            "difficulty": payload.difficulty,
            "category": payload.category,
            "evaluation_criteria": payload.evaluation_criteria,
            "response_format": payload.response_format,
            "response_time_seconds": payload.response_time_seconds,
            "position": payload.position,
            "meta": payload.meta,
        }
        return {key: value for key, value in mapping.items() if value is not None}

    def batch_questions(
        self,
        workflow_id: str,
        payload: WorkflowQuestionsBatchRequest,
        actor: PlatformActorContext | None = None,
    ) -> InterviewWorkflowResponse:
        """Create / update / delete / reorder questions in one authorized transaction."""
        if not payload.has_ops():
            raise HTTPException(
                status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
                detail="Batch must include at least one of: create, update, delete, reorder",
            )
        row = self._get_or_404(workflow_id, actor)
        wid = row.workflow_id

        updates = [
            {
                "question_id": item.question_id,
                "fields": self._patch_fields(item),
            }
            for item in payload.update
        ]
        creates = [
            self._create_item_dict(item, duration_minutes=row.duration_minutes)
            for item in payload.create
        ]

        try:
            qs = store.apply_question_batch(
                wid,
                delete_ids=list(payload.delete),
                updates=updates,
                creates=creates,
                reorder_ids=payload.reorder,
            )
        except store.QuestionBatchError as exc:
            raise HTTPException(status_code=exc.status_code, detail=exc.detail) from exc

        fields: dict[str, Any] = {}
        if qs:
            fields["status"] = "questions_ready"
        store.update_workflow(
            wid,
            company_id=_actor_company(actor),
            fields=fields,
        )
        resp = self.get(wid, actor=actor)
        resp.message = "Workflow questions updated"
        return resp
