"""Unified communication analysis — text quality + optional audio delivery/confidence."""

from __future__ import annotations

import re
from typing import Any

from app.schemas.audio_analysis import (
    AudioAnalysisRequest,
    ConfidenceIndicators,
    DeliveryScore,
    PauseStats,
    SpeechPatterns,
)
from app.schemas.common import JobStatus
from app.schemas.communication_analysis import (
    CommunicationAnalysisRequest,
    CommunicationAnalysisResponse,
    CommunicationDimension,
)
from app.services.audio.analysis import AudioAnalysisService
from app.services.audio.voice_scoring import score_voice_analysis
from app.services.shared.ai_generate import generate_json

_HEDGE = ("maybe", "i think", "sort of", "kind of", "probably", "not sure", "um", "uh")
_FILLER = ("basically", "actually", "literally", "you know", "i mean")
_ORG = ("first", "second", "then", "next", "finally", "overall", "in summary", "because")


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


def _texts(payload: CommunicationAnalysisRequest) -> list[tuple[str | None, str]]:
    out: list[tuple[str | None, str]] = []
    if payload.text and payload.text.strip():
        out.append((payload.question, payload.text.strip()))
    for t in payload.transcript:
        if (t.role or "").lower() == "candidate" and (t.text or "").strip():
            out.append((None, 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:
            out.append(((a.get("question") or payload.question), ans))
    return out


def _tokenize(text: str) -> set[str]:
    return {t for t in re.findall(r"[a-z0-9+]{3,}", text.lower())}


def _blob_text(payload: CommunicationAnalysisRequest, extra: str | None = None) -> str:
    parts = [a for _, a in _texts(payload)]
    if extra and extra.strip():
        parts.append(extra.strip())
    return " ".join(parts)


def _clean_list(items: Any, limit: int) -> list[str]:
    out: list[str] = []
    seen: set[str] = set()
    for s in items or []:
        if not isinstance(s, str):
            continue
        line = " ".join(s.split()).strip()
        if not line:
            continue
        key = line.lower()
        if key in seen:
            continue
        seen.add(key)
        out.append(line[:220])
        if len(out) >= limit:
            break
    return out


def _local_text(payload: CommunicationAnalysisRequest, blob_override: str | None = None) -> dict[str, Any]:
    pairs = _texts(payload)
    blob = (blob_override or "").strip() or " ".join(a for _, a in pairs)
    if not blob.strip():
        empty = lambda key, label: {  # noqa: E731
            "key": key,
            "label": label,
            "score": 0.0,
            "evidence": [],
            "gaps": ["No candidate text provided"],
        }
        return {
            "communication_score": 0.0,
            "clarity": empty("clarity", "Clarity"),
            "structure": empty("structure", "Structure"),
            "relevance": empty("relevance", "Relevance"),
            "conciseness": empty("conciseness", "Conciseness"),
            "summary": "No text to analyze.",
            "strengths": [],
            "weaknesses": ["No transcript or answer text provided"],
            "actionable_feedback": [
                "Provide answer text or a transcript to score communication"
            ],
        }

    lower = blob.lower()
    words = re.findall(r"\w+", lower)
    sentences = max(1, sum(blob.count(p) for p in ".!?") or (1 if blob else 0))
    avg_sentence = len(words) / sentences
    hedges = sum(1 for h in _HEDGE if h in lower)
    fillers = sum(1 for f in _FILLER if f in lower)
    org_hits = sum(1 for o in _ORG if o in lower)

    clarity = _clamp01(
        0.55
        + (0.15 if 8 <= avg_sentence <= 28 else -0.1)
        - 0.05 * min(hedges, 4)
        - 0.04 * min(fillers, 4)
        + (0.1 if len(words) >= 20 else 0)
    )

    q_tokens: set[str] = set()
    if payload.question:
        q_tokens |= _tokenize(payload.question)
    for q, _ in pairs:
        if q:
            q_tokens |= _tokenize(q)
    a_tokens = _tokenize(blob)
    overlap = (len(q_tokens & a_tokens) / max(1, len(q_tokens))) if q_tokens else 0.45
    relevance = _clamp01(0.25 + 0.7 * overlap)

    structure = _clamp01(
        0.3 + 0.12 * min(org_hits, 4) + (0.15 if sentences >= 3 else 0.05)
    )

    n = len(words)
    if n < 8:
        conciseness = 0.35
        conc_gap = "Too brief to judge concise, complete communication"
    elif n <= 120:
        conciseness = 0.85
        conc_gap = None
    elif n <= 220:
        conciseness = 0.65
        conc_gap = "Could tighten wording"
    else:
        conciseness = _clamp01(0.4 - 0.05 * fillers)
        conc_gap = "Answer is lengthy; trim repetition"

    dims = {
        "clarity": {
            "key": "clarity",
            "label": "Clarity",
            "score": round(clarity, 3),
            "evidence": [
                f"Avg words/sentence ≈ {avg_sentence:.1f}",
                f"Hedge/filler cues: {hedges + fillers}",
            ],
            "gaps": ([] if clarity >= 0.6 else ["Reduce hedging; use direct statements"]),
        },
        "structure": {
            "key": "structure",
            "label": "Structure",
            "score": round(structure, 3),
            "evidence": [f"Discourse markers: {org_hits}", f"Sentences: {sentences}"],
            "gaps": (
                []
                if structure >= 0.55
                else ["Use a clearer sequence: context → action → result"]
            ),
        },
        "relevance": {
            "key": "relevance",
            "label": "Relevance",
            "score": round(relevance, 3),
            "evidence": [
                f"Question-token overlap: {overlap:.2f}"
                if q_tokens
                else "No question provided — neutral relevance baseline"
            ],
            "gaps": ([] if relevance >= 0.55 else ["Stay closer to the question ask"]),
        },
        "conciseness": {
            "key": "conciseness",
            "label": "Conciseness",
            "score": round(conciseness, 3),
            "evidence": [f"Word count: {n}"],
            "gaps": ([conc_gap] if conc_gap else []),
        },
    }
    # Communication score from text dims only (no technical correctness, no audio blend)
    overall = (
        dims["clarity"]["score"]
        + dims["structure"]["score"]
        + dims["relevance"]["score"]
        + dims["conciseness"]["score"]
    ) / 4
    strengths = [d["label"] for d in dims.values() if d["score"] >= 0.7]
    weaknesses: list[str] = []
    actionable: list[str] = []
    for d in dims.values():
        for g in d["gaps"][:1]:
            if g not in weaknesses:
                weaknesses.append(g)
            if g not in actionable:
                actionable.append(g)
    return {
        "communication_score": round(overall, 3),
        **dims,
        "summary": (
            f"Communication score {overall:.2f} across clarity, structure, "
            f"relevance, and conciseness (not technical correctness)."
        ),
        "strengths": strengths or ["Some readable phrasing present"],
        "weaknesses": weaknesses[:5] or ["Needs clearer communication evidence"],
        "actionable_feedback": actionable[:3]
        or ["Add a clear opening, one concrete example, and a short close"],
    }


class CommunicationAnalysisService:
    def __init__(self) -> None:
        self._audio = AudioAnalysisService()

    async def analyze(
        self, payload: CommunicationAnalysisRequest
    ) -> CommunicationAnalysisResponse:
        # Never treat client-supplied feedback as ground truth
        options = dict(payload.options or {})
        for ignore in (
            "strengths",
            "weaknesses",
            "improvement_areas",
            "actionable_feedback",
            "precomputed_feedback",
            "confidence_score",
            "communication_score",
        ):
            options.pop(ignore, None)

        has_audio_source = bool(payload.audio_base64) or bool(payload.source_url)
        has_audio_features = bool(payload.audio_features)
        want_audio = payload.include_voice_delivery and (
            has_audio_source or has_audio_features
        )

        # --- Optional single audio pass (reuse transcript + features) ---
        audio_res = None
        stt_transcript: str | None = None
        delivery: DeliveryScore | None = None
        speech_patterns: SpeechPatterns | None = None
        confidence_indicators: ConfidenceIndicators | None = None
        pauses: PauseStats | None = None
        vocal_delivery: float | None = None
        pacing: float | None = None
        confidence_score: float | None = None
        certainty_band: str | None = None
        audio_duration_seconds: float | None = None
        speech_duration_seconds: float | None = None
        silence_percentage: float | None = None
        words_per_minute: float | None = None
        audio_quality = None
        audio_features: dict[str, Any] = {}
        transcription_status: str | None = None
        limitations: list[str] = []
        delivery_paused = True

        if want_audio and has_audio_source:
            audio_req = AudioAnalysisRequest(
                correlation_id=payload.correlation_id,
                interview_id=payload.interview_id or "comm-audio",
                audio_base64=payload.audio_base64,
                source_url=payload.source_url,
                audio_mime_type=payload.audio_mime_type,
                transcript_text=_blob_text(payload) or None,
                run_transcription=payload.run_transcription
                and not bool(_blob_text(payload)),
                language=payload.language,
                options=options,
            )
            audio_res = await self._audio.analyze(audio_req)
            transcription_status = audio_res.transcription_status
            if audio_res.status == JobStatus.SUCCEEDED:
                delivery = audio_res.delivery
                speech_patterns = audio_res.speech_patterns
                confidence_indicators = audio_res.confidence_indicators
                pauses = audio_res.pause_stats
                vocal_delivery = audio_res.overall_delivery_score
                if delivery is not None:
                    pacing = delivery.pacing_score
                if confidence_indicators is not None:
                    # Audio-derived only — never fabricate from text
                    confidence_score = confidence_indicators.score
                    certainty_band = confidence_indicators.band
                    # Drop linguistic-only confidence when no acoustic signal
                    if (
                        confidence_indicators.acoustic_score is None
                        and not has_audio_source
                    ):
                        confidence_score = None
                        certainty_band = None
                audio_duration_seconds = audio_res.audio_duration_seconds
                speech_duration_seconds = audio_res.speech_duration_seconds
                silence_percentage = audio_res.silence_percentage
                words_per_minute = audio_res.words_per_minute
                audio_quality = audio_res.audio_quality
                audio_features = dict(audio_res.features or {})
                limitations.extend(list(audio_res.limitations or []))
                if audio_res.transcript_used and audio_req.transcript_text:
                    stt_transcript = audio_req.transcript_text
                delivery_paused = delivery is None or delivery.score is None
            else:
                limitations.append(
                    audio_res.message or "Audio analysis failed; text-only communication scored"
                )
                transcription_status = audio_res.transcription_status or "failed"
        elif want_audio and has_audio_features:
            # Score delivery/confidence once from supplied features (no second GPT)
            scored = score_voice_analysis(
                features=dict(payload.audio_features),
                transcript_text=_blob_text(payload) or None,
                transcript_turns=list(payload.transcript),
            )
            delivery = DeliveryScore(**scored["delivery"])
            speech_patterns = SpeechPatterns(**scored["speech_patterns"])
            confidence_indicators = ConfidenceIndicators(
                **scored["confidence_indicators"]
            )
            vocal_delivery = scored.get("overall_score")
            pacing = delivery.pacing_score
            # Require acoustic evidence in features for confidence
            acoustic = confidence_indicators.acoustic_score
            if acoustic is not None:
                confidence_score = confidence_indicators.score
                certainty_band = confidence_indicators.band
            else:
                confidence_score = None
                certainty_band = None
                confidence_indicators = ConfidenceIndicators(
                    score=None,
                    band=None,
                    linguistic_score=confidence_indicators.linguistic_score,
                    acoustic_score=None,
                    linguistic_cues=list(confidence_indicators.linguistic_cues or []),
                    acoustic_cues=[],
                    note=(
                        "Confidence delivery score omitted — no acoustic evidence; "
                        "not inferred from text alone"
                    ),
                )
            audio_features = dict(payload.audio_features)
            limitations.extend(list(scored.get("limitations") or []))
            delivery_paused = delivery.score is None
        else:
            limitations.append(
                "No audio provided — vocal delivery, pacing, pauses, and "
                "confidence score are null (not inferred from text)"
            )

        # --- Single text communication GPT/local pass ---
        text_blob = _blob_text(payload, stt_transcript)
        system = (
            "Analyze interview COMMUNICATION QUALITY from transcript/answer text only. "
            "Do NOT score technical correctness, domain knowledge, or hiring fit. "
            "Do NOT infer confidence, personality, or vocal delivery from text. "
            "Derive strengths, weaknesses, and actionable feedback yourself from the "
            "text — ignore any pre-supplied feedback. "
            "Return JSON only: {"
            "\"communication_score\":0-1,"
            "\"clarity\":{key,label,score,evidence[],gaps[]},"
            "\"structure\":{key,label,score,evidence[],gaps[]},"
            "\"relevance\":{key,label,score,evidence[],gaps[]},"
            "\"conciseness\":{key,label,score,evidence[],gaps[]},"
            "\"summary\":string,"
            "\"strengths\":[string],"
            "\"weaknesses\":[string],"
            "\"actionable_feedback\":[string]"
            "}"
        )
        pairs = _texts(payload)
        user = (
            f"Role: {payload.role_title}\nQuestion: {payload.question}\n"
            f"Answers/transcript: {pairs or text_blob or 'none'}\n"
            f"Language: {payload.language}"
        )
        data, stub, provider = await generate_json(
            system=system,
            user=user,
            local_factory=lambda: _local_text(payload, text_blob or None),
        )
        if not isinstance(data, dict):
            data = _local_text(payload, text_blob or None)
            stub = True

        def dim(key: str, label: str, alt_key: str | None = None) -> CommunicationDimension:
            raw = data.get(key) or (data.get(alt_key) if alt_key else None)
            if not isinstance(raw, dict):
                raw = _local_text(payload, text_blob or None).get(key) or {
                    "key": key,
                    "label": label,
                    "score": 0.0,
                    "evidence": [],
                    "gaps": [],
                }
            return CommunicationDimension(
                key=str(raw.get("key") or key),
                label=str(raw.get("label") or label),
                score=_clamp01(raw.get("score")),
                evidence=[str(e) for e in (raw.get("evidence") or [])][:5],
                gaps=[str(g) for g in (raw.get("gaps") or [])][:5],
            )

        clarity = dim("clarity", "Clarity")
        structure = dim("structure", "Structure", alt_key="organization")
        relevance = dim("relevance", "Relevance")
        conciseness = dim("conciseness", "Conciseness")

        text_score = data.get("communication_score")
        if text_score is None:
            text_score = data.get("overall_score")
        if text_score is None:
            text_score = (
                clarity.score + structure.score + relevance.score + conciseness.score
            ) / 4
        communication_score = round(_clamp01(text_score), 3)

        strengths = _clean_list(data.get("strengths"), 5)
        weaknesses = _clean_list(
            data.get("weaknesses") or data.get("improvement_areas"), 5
        )
        actionable = _clean_list(data.get("actionable_feedback"), 3)
        if not actionable:
            actionable = _clean_list(weaknesses, 3)
        # Merge audio delivery gaps into actionable (no second GPT)
        if delivery is not None and delivery.gaps:
            for g in delivery.gaps:
                if len(actionable) >= 3:
                    break
                if g and g not in actionable:
                    actionable.append(g)
        if delivery is not None and delivery.score is not None and delivery.score >= 0.7:
            if "Vocal delivery" not in strengths and len(strengths) < 5:
                strengths.append("Vocal delivery")

        summary = data.get("summary") or (
            f"Communication score {communication_score:.2f} "
            f"(clarity/structure/relevance; not technical correctness)."
        )
        if not delivery_paused and vocal_delivery is not None:
            summary = (
                f"{summary} Vocal delivery={vocal_delivery:.2f}"
                + (
                    f", confidence delivery={confidence_score:.2f}."
                    if confidence_score is not None
                    else "."
                )
            )

        return CommunicationAnalysisResponse(
            correlation_id=payload.correlation_id,
            interview_id=payload.interview_id,
            status=JobStatus.SUCCEEDED,
            stub=stub,
            message=(
                f"Communication analysis via {provider}"
                + (" + audio delivery/confidence" if not delivery_paused else " (text only)")
            ),
            communication_score=communication_score,
            overall_score=communication_score,
            clarity=clarity,
            structure=structure,
            relevance=relevance,
            organization=structure.model_copy(
                update={"key": "organization", "label": "Organization"}
            ),
            conciseness=conciseness,
            strengths=strengths,
            weaknesses=weaknesses,
            improvement_areas=weaknesses,
            actionable_feedback=actionable[:3],
            summary=summary,
            vocal_delivery=vocal_delivery if not delivery_paused else None,
            pacing=pacing if not delivery_paused else None,
            pauses=pauses,
            confidence_score=confidence_score,
            certainty_band=certainty_band,
            delivery=delivery if not delivery_paused else None,
            speech_patterns=speech_patterns if not delivery_paused else None,
            confidence_indicators=confidence_indicators,
            audio_duration_seconds=audio_duration_seconds,
            speech_duration_seconds=speech_duration_seconds,
            silence_percentage=silence_percentage,
            words_per_minute=words_per_minute,
            audio_quality=audio_quality,
            audio_features=audio_features,
            audio_delivery_paused=delivery_paused,
            transcript_used=bool(text_blob),
            transcription_status=transcription_status,
            limitations=limitations[:12],
        )
