"""Unified behavioral analysis — text + voice + face fused into one score."""

from __future__ import annotations

import logging
import re
from typing import Any

from app.schemas.behavioral_analysis import (
    BehavioralAnalysisRequest,
    BehavioralAnalysisResponse,
    BehavioralCompetencyScore,
    BehavioralCue,
    BehavioralDimensionScore,
    BehavioralFusion,
    ModalityScore,
)
from app.schemas.common import JobStatus
from app.services.shared.ai_generate import generate_json

logger = logging.getLogger(__name__)

DEFAULT_COMPETENCIES: list[tuple[str, str, tuple[str, ...]]] = [
    (
        "collaboration",
        "Collaboration",
        ("team", "collaborat", "stakeholder", "partner", "cross-functional", "worked with"),
    ),
    (
        "leadership",
        "Leadership",
        ("led", "lead", " mentored", "mentor", "drove", "owned the", "influenc"),
    ),
    (
        "adaptability",
        "Adaptability",
        ("adapt", "pivot", "changed", "learned", "ambigu", "trade-off", "tradeoff"),
    ),
    (
        "communication",
        "Communication",
        ("explain", "communicat", "present", "align", "clarif", "documented"),
    ),
    (
        "accountability",
        "Accountability",
        ("accountab", "responsible", "owned", "my mistake", "i fixed", "follow-through"),
    ),
]

# STAR / answer structure cues
_STRUCTURE_CUES = {
    "situation": ("situation", "context", "background", "at the time", "when i", "previously"),
    "task": ("task", "goal", "objective", "needed to", "was asked", "responsibility"),
    "action": ("i ", "we ", "implemented", "designed", "built", "decided", "approach"),
    "result": ("result", "outcome", "impact", "improved", "reduced", "increased", "metric", "%"),
}

_EXAMPLE_CUES = (
    "for example",
    "e.g",
    "such as",
    "one time",
    "in one project",
    "at my previous",
    "at acme",
    "specifically",
    "concrete",
    "instance",
)

_OWNERSHIP_CUES = (
    "i owned",
    "i led",
    "i decided",
    "i implemented",
    "my responsibility",
    "i was accountable",
    "i drove",
    "i shipped",
    "i fixed",
    "i designed",
)

_WEAK_OWNERSHIP = (
    "we just",
    "they did",
    "the team did",
    "someone else",
    "not sure",
    "i was told",
)


def _clamp01(value: Any, default: float = 0.0) -> float:
    try:
        v = float(value)
    except (TypeError, ValueError):
        return default
    return max(0.0, min(1.0, v))


def _cue_evidence(value: Any) -> str | None:
    """BehavioralCue.evidence is str | None; LLM/local often return a list."""
    if value is None:
        return None
    if isinstance(value, str):
        text = value.strip()
        return text or None
    if isinstance(value, (list, tuple)):
        parts = [str(x).strip() for x in value if x is not None and str(x).strip()]
        return "; ".join(parts) if parts else None
    text = str(value).strip()
    return text or None


def _candidate_texts(payload: BehavioralAnalysisRequest) -> list[str]:
    texts: list[str] = []
    for t in payload.transcript:
        if (t.role or "").lower() == "candidate" and (t.text or "").strip():
            texts.append(t.text.strip())
    for a in payload.answers:
        if not isinstance(a, dict):
            continue
        ans = (a.get("answer") or a.get("candidate_answer") or "").strip()
        if ans:
            texts.append(ans)
    return texts


def _count_hits(blob: str, cues: tuple[str, ...]) -> int:
    return sum(1 for c in cues if c in blob)


def _local_structure(blob: str, answers: list[str]) -> BehavioralDimensionScore:
    present = []
    missing = []
    hits = 0
    for key, cues in _STRUCTURE_CUES.items():
        if _count_hits(blob, cues) > 0:
            present.append(key)
            hits += 1
        else:
            missing.append(key)
    # Length / multi-sentence structure
    sentences = sum(blob.count(p) for p in ".!?") + (1 if blob else 0)
    length_bonus = 0.15 if len(blob) > 120 else 0.05 if len(blob) > 40 else 0.0
    score = _clamp01(0.15 + 0.18 * hits + length_bonus + (0.1 if sentences >= 3 else 0))
    evidence = []
    if present:
        evidence.append("Structure signals present: " + ", ".join(present))
    if answers:
        evidence.append(f"Analyzed {len(answers)} candidate answer(s)")
    gaps = []
    if missing:
        gaps.append("Weak or missing STAR parts: " + ", ".join(missing))
    if len(blob) < 40:
        gaps.append("Answers too short to show clear structure")
    return BehavioralDimensionScore(
        key="answer_structure",
        label="Answer structure",
        score=round(score, 3),
        evidence=evidence,
        gaps=gaps,
    )


def _local_examples(blob: str) -> BehavioralDimensionScore:
    hits = _count_hits(blob, _EXAMPLE_CUES)
    # Proper nouns / project-ish tokens as weak example signal
    proper = len(re.findall(r"\b[A-Z][a-z]{2,}\b", blob))
    digits = len(re.findall(r"\d+", blob))
    score = _clamp01(0.2 + 0.15 * min(hits, 3) + 0.05 * min(proper, 3) + 0.08 * min(digits, 2))
    evidence = []
    gaps = []
    if hits:
        evidence.append(f"Example phrasing detected ({hits} cue hits)")
    if digits:
        evidence.append("Includes numeric details (possible metrics)")
    if hits == 0 and digits == 0:
        gaps.append("Few concrete examples or metrics in answers")
    if score < 0.45:
        gaps.append("Add specific project/story examples with outcomes")
    return BehavioralDimensionScore(
        key="examples",
        label="Examples",
        score=round(score, 3),
        evidence=evidence or ["Limited example signals"],
        gaps=gaps,
    )


def _local_ownership(blob: str) -> BehavioralDimensionScore:
    own = _count_hits(blob, _OWNERSHIP_CUES)
    # First-person agency
    i_count = len(re.findall(r"\bi\b", blob))
    we_count = len(re.findall(r"\bwe\b", blob))
    weak = _count_hits(blob, _WEAK_OWNERSHIP)
    score = _clamp01(
        0.25
        + 0.12 * min(own, 4)
        + 0.03 * min(i_count, 8)
        - 0.08 * weak
        + (0.05 if i_count > we_count else -0.05)
    )
    evidence = []
    gaps = []
    if own or i_count >= 3:
        evidence.append("First-person ownership language present")
    if we_count > i_count * 2 and i_count < 2:
        gaps.append("Heavy 'we' language without clear personal ownership")
    if weak:
        gaps.append("Some deflecting / low-agency phrasing")
    if score < 0.5:
        gaps.append("Clarify what you personally owned vs the team")
    return BehavioralDimensionScore(
        key="ownership",
        label="Ownership",
        score=round(score, 3),
        evidence=evidence or ["Ownership signals are limited"],
        gaps=gaps,
    )


def _local_competencies(
    blob: str,
    requested: list[str],
) -> list[BehavioralCompetencyScore]:
    catalog = list(DEFAULT_COMPETENCIES)
    if requested:
        # Map requested names onto catalog or create generic entries
        wanted = {r.strip().lower().replace(" ", "_") for r in requested if r.strip()}
        selected = [c for c in catalog if c[0] in wanted or c[1].lower() in {
            r.lower() for r in requested
        }]
        for r in requested:
            key = r.strip().lower().replace(" ", "_")
            if not any(c[0] == key for c in selected):
                selected.append((key, r.strip().title(), (key.replace("_", " "),)))
        catalog = selected or catalog

    out: list[BehavioralCompetencyScore] = []
    for key, label, cues in catalog:
        hits = _count_hits(blob, cues)
        score = _clamp01(0.2 + 0.18 * min(hits, 4))
        evidence = []
        if hits:
            evidence.append(f"Competency cues for {label}: {hits} hit(s)")
        needs = score < 0.45
        out.append(
            BehavioralCompetencyScore(
                key=key,
                label=label,
                score=round(score, 3),
                evidence=evidence or [f"Limited {label.lower()} evidence in answers"],
                needs_more_evidence=needs,
            )
        )
    return out


def _local_analysis(payload: BehavioralAnalysisRequest) -> dict[str, Any]:
    answers = _candidate_texts(payload)
    blob = " ".join(answers).lower()
    if not blob.strip():
        empty_dim = lambda key, label: BehavioralDimensionScore(  # noqa: E731
            key=key,
            label=label,
            score=0.0,
            evidence=[],
            gaps=["No candidate answers provided"],
        ).model_dump()
        return {
            "overall_score": 0.0,
            "overall_confidence": 0.0,
            "tone_summary": "No candidate responses available for behavioral analysis.",
            "summary": "Provide interview transcript or answers to assess behavior.",
            "answer_structure": empty_dim("answer_structure", "Answer structure"),
            "examples": empty_dim("examples", "Examples"),
            "ownership": empty_dim("ownership", "Ownership"),
            "competencies": [
                BehavioralCompetencyScore(
                    key=k,
                    label=l,
                    score=0.0,
                    evidence=[],
                    needs_more_evidence=True,
                ).model_dump()
                for k, l, _ in DEFAULT_COMPETENCIES
            ],
            "strengths": [],
            "improvement_areas": ["Collect candidate answers before analyzing behavior"],
            "cues": [],
            "flags": ["empty_transcript"],
        }

    structure = _local_structure(blob, answers)
    examples = _local_examples(blob)
    ownership = _local_ownership(blob)
    competencies = _local_competencies(blob, payload.competencies)

    overall = (
        structure.score * 0.25
        + examples.score * 0.25
        + ownership.score * 0.25
        + (sum(c.score for c in competencies) / max(1, len(competencies))) * 0.25
    )
    confidence = _clamp01(0.4 + 0.4 * ownership.score + 0.2 * structure.score)

    strengths = []
    improvements = []
    for dim in (structure, examples, ownership):
        if dim.score >= 0.65:
            strengths.append(f"{dim.label}: {dim.evidence[0] if dim.evidence else 'solid'}")
        if dim.gaps:
            improvements.extend(dim.gaps[:1])
    for c in competencies:
        if c.score >= 0.65:
            strengths.append(f"{c.label} competency signal")
        elif c.needs_more_evidence:
            improvements.append(f"Need more evidence for {c.label}")

    summary = (
        f"Behavioral profile across {len(answers)} answer(s): "
        f"structure {structure.score:.2f}, examples {examples.score:.2f}, "
        f"ownership {ownership.score:.2f}. Overall {overall:.2f}."
    )
    cues = [
        BehavioralCue(
            name=structure.key, score=structure.score, evidence="; ".join(structure.evidence)
        ).model_dump(),
        BehavioralCue(
            name=examples.key, score=examples.score, evidence="; ".join(examples.evidence)
        ).model_dump(),
        BehavioralCue(
            name=ownership.key, score=ownership.score, evidence="; ".join(ownership.evidence)
        ).model_dump(),
    ]
    for c in competencies:
        cues.append(
            BehavioralCue(
                name=c.key,
                score=c.score,
                evidence="; ".join(c.evidence),
            ).model_dump()
        )

    flags = []
    if ownership.score < 0.4:
        flags.append("low_ownership")
    if examples.score < 0.4:
        flags.append("weak_examples")
    if structure.score < 0.4:
        flags.append("weak_structure")

    return {
        "overall_score": round(overall, 3),
        "overall_confidence": round(confidence, 3),
        "tone_summary": (
            "Composed and specific."
            if overall >= 0.7
            else "Mixed behavioral signals; probe for clearer ownership and examples."
        ),
        "summary": summary,
        "answer_structure": structure.model_dump(),
        "examples": examples.model_dump(),
        "ownership": ownership.model_dump(),
        "competencies": [c.model_dump() for c in competencies],
        "strengths": strengths[:6],
        "improvement_areas": improvements[:6],
        "cues": cues,
        "flags": flags,
    }


def _parse_dimension(raw: Any, key: str, label: str) -> BehavioralDimensionScore:
    if isinstance(raw, dict):
        return BehavioralDimensionScore(
            key=str(raw.get("key") or key),
            label=str(raw.get("label") or label),
            score=_clamp01(raw.get("score"), 0.0),
            evidence=[str(e) for e in (raw.get("evidence") or [])][:5],
            gaps=[str(g) for g in (raw.get("gaps") or [])][:5],
        )
    return BehavioralDimensionScore(key=key, label=label, score=0.0)


def _score_voice_modality(
    *,
    features: dict[str, Any],
    transcript_blob: str,
) -> ModalityScore:
    """Voice delivery / fluency cues from audio-analysis features."""
    if not features:
        return ModalityScore(
            modality="voice",
            available=False,
            gaps=["No audio_features or audio_base64 provided"],
        )
    from app.services.audio.voice_scoring import score_voice_analysis

    scored = score_voice_analysis(features=features, transcript_text=transcript_blob or None)
    delivery = scored.get("delivery") or {}
    confidence = scored.get("confidence_indicators") or {}
    patterns = scored.get("speech_patterns") or {}
    delivery_score = _clamp01(delivery.get("score"), 0.5)
    conf_score = _clamp01(confidence.get("score"), 0.5)
    fluency = _clamp01(patterns.get("fluency_score"), delivery_score)
    voice_score = round(0.45 * delivery_score + 0.35 * conf_score + 0.20 * fluency, 4)
    evidence = list(delivery.get("evidence") or [])[:2]
    if patterns.get("speaking_rate_band"):
        evidence.append(f"Speaking rate: {patterns.get('speaking_rate_band')}")
    gaps = list(delivery.get("gaps") or [])[:3]
    if voice_score < 0.45:
        gaps.append("Voice delivery cues below mid range")
    return ModalityScore(
        modality="voice",
        available=True,
        score=voice_score,
        evidence=evidence[:4],
        gaps=gaps[:4],
    )


def _score_face_modality(signals: dict[str, Any]) -> ModalityScore:
    """Face/video presence + liveness (+ optional identity) cues."""
    if not signals:
        return ModalityScore(
            modality="face",
            available=False,
            gaps=["No face_signals / video_signals provided"],
        )

    evidence: list[str] = []
    gaps: list[str] = []
    parts: list[float] = []

    face_ratio = signals.get("faces_detected_ratio")
    if face_ratio is not None:
        fr = _clamp01(face_ratio, 0.0)
        parts.append(fr)
        evidence.append(f"Face presence ratio={fr:.2f}")
        if fr < 0.5:
            gaps.append("Candidate face often not detected in frames")

    liveness_passed = signals.get("liveness_passed")
    liveness_score = signals.get("liveness_score")
    if liveness_score is not None:
        ls = _clamp01(liveness_score, 0.0)
        parts.append(ls if liveness_passed is not False else min(ls, 0.35))
        evidence.append(f"Liveness score={ls:.2f} (passed={liveness_passed})")
        if liveness_passed is False:
            gaps.append("Liveness check failed")
    elif liveness_passed is True:
        parts.append(0.85)
        evidence.append("Liveness passed")
    elif liveness_passed is False:
        parts.append(0.2)
        gaps.append("Liveness check failed")

    identity = signals.get("identity_matched")
    if identity is True:
        parts.append(0.9)
        evidence.append("Identity matched ID/registered photo")
    elif identity is False:
        parts.append(0.25)
        gaps.append("Identity mismatch vs ID/registered photo")

    engagement = signals.get("engagement_score")
    if engagement is not None:
        eg = _clamp01(engagement, 0.0)
        parts.append(eg)
        evidence.append(f"Engagement={eg:.2f}")

    # Multi-face penalty signal
    multi = signals.get("multi_face_frames")
    if multi is not None:
        try:
            mf = int(multi)
            if mf > 0:
                parts.append(max(0.2, 1.0 - 0.15 * mf))
                gaps.append(f"Multi-face frames detected ({mf})")
        except (TypeError, ValueError):
            pass

    # Generic numeric scores in signals map
    for key in ("antispoof_score", "match_score", "attention_score"):
        if key in signals and signals[key] is not None:
            parts.append(_clamp01(signals[key], 0.5))

    if not parts:
        return ModalityScore(
            modality="face",
            available=False,
            gaps=["Face/video signals present but no usable scores"],
        )

    score = round(sum(parts) / len(parts), 4)
    return ModalityScore(
        modality="face",
        available=True,
        score=score,
        evidence=evidence[:5],
        gaps=gaps[:4],
    )


def _fuse_modalities(
    *,
    text: ModalityScore,
    voice: ModalityScore,
    face: ModalityScore,
    text_weight: float,
    voice_weight: float,
    face_weight: float,
) -> BehavioralFusion:
    """Weighted fusion; redistribute weights across available modalities only."""
    raw = [
        ("text", text, float(text_weight)),
        ("voice", voice, float(voice_weight)),
        ("face", face, float(face_weight)),
    ]
    available = [(n, m, w) for n, m, w in raw if m.available and m.score is not None]
    if not available:
        return BehavioralFusion(
            text=text,
            voice=voice,
            face=face,
            unified_score=0.0,
            modalities_used=[],
            formula="no modalities available",
        )

    total_w = sum(max(0.0, w) for _, _, w in available) or 1.0
    used: list[str] = []
    pieces: list[str] = []
    unified = 0.0
    weight_map: dict[str, float] = {}
    for name, mod, w in available:
        nw = max(0.0, w) / total_w
        weight_map[name] = nw
        unified += nw * float(mod.score or 0.0)
        used.append(name)
        pieces.append(f"{nw:.2f}*{name}({mod.score:.2f})")

    def _with_weight(mod: ModalityScore) -> ModalityScore:
        return ModalityScore(
            modality=mod.modality,
            available=mod.available,
            score=mod.score,
            weight_used=weight_map.get(mod.modality),
            evidence=mod.evidence,
            gaps=mod.gaps,
        )

    return BehavioralFusion(
        text=_with_weight(text),
        voice=_with_weight(voice),
        face=_with_weight(face),
        unified_score=round(_clamp01(unified), 4),
        modalities_used=used,
        formula=" + ".join(pieces),
    )


class BehavioralAnalysisService:
    async def analyze(
        self, payload: BehavioralAnalysisRequest
    ) -> BehavioralAnalysisResponse:
        system = (
            "You analyze interview behavior from candidate answers. "
            "Assess answer structure (STAR-like), use of concrete examples, "
            "personal ownership, and behavioral competencies. "
            "Return JSON only: {"
            "\"overall_score\":0-1,"
            "\"overall_confidence\":0-1,"
            "\"tone_summary\":string,"
            "\"summary\":string,"
            "\"answer_structure\":{\"key\",\"label\",\"score\",\"evidence\":[],\"gaps\":[]},"
            "\"examples\":{\"key\",\"label\",\"score\",\"evidence\":[],\"gaps\":[]},"
            "\"ownership\":{\"key\",\"label\",\"score\",\"evidence\":[],\"gaps\":[]},"
            "\"competencies\":[{\"key\",\"label\",\"score\",\"evidence\":[],\"needs_more_evidence\":bool}],"
            "\"strengths\":[],\"improvement_areas\":[],"
            "\"cues\":[{\"name\",\"score\",\"evidence\"}],\"flags\":[]"
            "}. Ground claims in the provided answers only. "
            "Do not invent voice/face scores — those are fused server-side."
        )
        answers = _candidate_texts(payload)
        face_signals = {**(payload.video_signals or {}), **(payload.face_signals or {})}
        user = (
            f"Interview: {payload.interview_id}\n"
            f"Role: {payload.role_title or 'n/a'}\n"
            f"JD: {payload.job_description or 'n/a'}\n"
            f"Mode: {payload.mode.value}\n"
            f"Competency focus: {payload.competencies or [c[0] for c in DEFAULT_COMPETENCIES]}\n"
            f"Candidate answers: {answers}\n"
            f"Full transcript: {[{'role': t.role, 'text': t.text} for t in payload.transcript]}\n"
            f"Audio features keys: {list((payload.audio_features or {}).keys())}\n"
            f"Face/video signal keys: {list(face_signals.keys())}"
        )

        data, stub, provider = await generate_json(
            system=system, user=user, local_factory=lambda: _local_analysis(payload)
        )
        if not isinstance(data, dict):
            data = _local_analysis(payload)
            stub = True
            provider = "local"

        local = _local_analysis(payload)
        structure = _parse_dimension(
            data.get("answer_structure") or local["answer_structure"],
            "answer_structure",
            "Answer structure",
        )
        examples = _parse_dimension(
            data.get("examples") or local["examples"], "examples", "Examples"
        )
        ownership = _parse_dimension(
            data.get("ownership") or local["ownership"], "ownership", "Ownership"
        )

        comps_raw = data.get("competencies") or local["competencies"]
        competencies: list[BehavioralCompetencyScore] = []
        for c in comps_raw:
            if not isinstance(c, dict):
                continue
            competencies.append(
                BehavioralCompetencyScore(
                    key=str(c.get("key") or "competency"),
                    label=str(c.get("label") or c.get("key") or "Competency"),
                    score=_clamp01(c.get("score"), 0.0),
                    evidence=[str(e) for e in (c.get("evidence") or [])][:5],
                    needs_more_evidence=bool(
                        c.get("needs_more_evidence", _clamp01(c.get("score"), 0) < 0.45)
                    ),
                )
            )
        if not competencies:
            competencies = [
                BehavioralCompetencyScore.model_validate(c)
                for c in local["competencies"]
            ]

        # --- Text modality (from structure / examples / ownership / competencies) ---
        text_overall = (
            structure.score * 0.25
            + examples.score * 0.25
            + ownership.score * 0.25
            + (sum(c.score for c in competencies) / max(1, len(competencies))) * 0.25
        )
        text_available = bool(answers)
        text_mod = ModalityScore(
            modality="text",
            available=text_available,
            score=round(text_overall, 4) if text_available else None,
            evidence=[
                f"structure={structure.score:.2f}",
                f"examples={examples.score:.2f}",
                f"ownership={ownership.score:.2f}",
            ]
            if text_available
            else [],
            gaps=[] if text_available else ["No candidate text for behavioral text channel"],
        )

        # --- Voice modality ---
        audio_features = dict(payload.audio_features or {})
        if payload.audio_base64 and not audio_features:
            try:
                from app.schemas.audio_analysis import AudioAnalysisRequest
                from app.services.audio.analysis import AudioAnalysisService

                audio_res = await AudioAnalysisService().analyze(
                    AudioAnalysisRequest(
                        interview_id=payload.interview_id,
                        audio_base64=payload.audio_base64,
                        audio_mime_type=payload.audio_mime_type,
                        transcript_text=" ".join(answers) or None,
                        run_transcription=False,
                    )
                )
                audio_features = dict(audio_res.features or {})
                if audio_res.overall_delivery_score is not None:
                    audio_features.setdefault(
                        "overall_delivery_score", audio_res.overall_delivery_score
                    )
                stub = stub and bool(audio_res.stub)
            except Exception as exc:  # noqa: BLE001
                logger.info("Behavioral voice channel skipped: %s", type(exc).__name__)
                audio_features = {}

        voice_mod = _score_voice_modality(
            features=audio_features,
            transcript_blob=" ".join(answers),
        )

        # --- Face modality ---
        face_mod = _score_face_modality(face_signals)

        fusion = _fuse_modalities(
            text=text_mod,
            voice=voice_mod,
            face=face_mod,
            text_weight=payload.text_weight,
            voice_weight=payload.voice_weight,
            face_weight=payload.face_weight,
        )

        # overall_score = unified fusion (text-only when voice/face absent)
        overall = fusion.unified_score
        # Confidence rises with more modalities and stronger text evidence
        modality_bonus = 0.15 * max(0, len(fusion.modalities_used) - 1)
        base_conf = _clamp01(
            data.get("overall_confidence")
            if data.get("overall_confidence") is not None
            else local.get("overall_confidence")
            or (0.4 + 0.4 * ownership.score + 0.2 * structure.score)
        )
        confidence = _clamp01(base_conf + modality_bonus)

        cues = [
            BehavioralCue(
                name=str(c.get("name", "")),
                score=(
                    _clamp01(c.get("score"))
                    if c.get("score") is not None
                    else None
                ),
                evidence=_cue_evidence(c.get("evidence")),
            )
            for c in (data.get("cues") or local.get("cues") or [])
            if isinstance(c, dict) and c.get("name")
        ]
        # Add modality cues
        for mod in (fusion.text, fusion.voice, fusion.face):
            if mod.available and mod.score is not None:
                cues.append(
                    BehavioralCue(
                        name=f"modality_{mod.modality}",
                        score=mod.score,
                        evidence="; ".join(mod.evidence) or None,
                    )
                )

        flags = list(data.get("flags") or local.get("flags") or [])
        if voice_mod.available and (voice_mod.score or 0) < 0.4:
            flags.append("weak_voice_delivery")
        if face_mod.available and (face_mod.score or 0) < 0.4:
            flags.append("weak_face_signals")
        if len(fusion.modalities_used) >= 2:
            flags.append("multimodal_fusion")

        strengths = list(data.get("strengths") or local.get("strengths") or [])[:6]
        improvements = list(
            data.get("improvement_areas") or local.get("improvement_areas") or []
        )[:6]
        for mod in (voice_mod, face_mod):
            if mod.available and mod.gaps:
                improvements.extend(mod.gaps[:1])
            if mod.available and mod.score is not None and mod.score >= 0.7 and mod.evidence:
                strengths.append(f"{mod.modality.title()}: {mod.evidence[0]}")

        channels = "+".join(fusion.modalities_used) or "none"
        summary = (
            data.get("summary")
            or local.get("summary")
            or f"Unified behavioral score {overall:.2f} from [{channels}]."
        )
        if len(fusion.modalities_used) > 1:
            summary = (
                f"Unified behavioral score {overall:.2f} "
                f"(modalities: {channels}; {fusion.formula}). "
                f"{summary}"
            )

        return BehavioralAnalysisResponse(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=f"Unified behavioral analysis via {provider} [{channels}]",
            overall_score=overall,
            overall_confidence=round(confidence, 4),
            fusion=fusion,
            tone_summary=data.get("tone_summary") or local.get("tone_summary"),
            summary=summary,
            answer_structure=structure,
            examples=examples,
            ownership=ownership,
            competencies=competencies,
            strengths=strengths[:8],
            improvement_areas=improvements[:8],
            cues=cues,
            flags=flags,
        )
