"""Deterministic speech-pattern / delivery / confidence-indicator scoring.

Uses objective acoustics (Librosa) + transcript cues. Does NOT infer personality,
honesty, intelligence, or hiring suitability.
"""

from __future__ import annotations

import re
from typing import Any

_HEDGE = ("maybe", "i think", "sort of", "kind of", "probably", "not sure", "i guess")
_FILLER = ("um", "uh", "erm", "basically", "actually", "literally", "you know", "i mean")
_ASSERT = (
    "i decided",
    "i led",
    "i owned",
    "we measured",
    "the result",
    "for example",
    "specifically",
)


def _clamp01(v: float) -> float:
    return max(0.0, min(1.0, float(v)))


def _f(d: dict[str, Any], key: str, default: float | None = None) -> float | None:
    v = d.get(key)
    if v is None:
        return default
    try:
        return float(v)
    except (TypeError, ValueError):
        return default


def _transcript_blob(text: str | None, turns: list[Any] | None = None) -> str:
    parts: list[str] = []
    if text and text.strip():
        parts.append(text.strip())
    for t in turns or []:
        if isinstance(t, dict):
            role = (t.get("role") or "").lower()
            body = (t.get("text") or "").strip()
            if role in {"", "candidate"} and body:
                parts.append(body)
        else:
            role = (getattr(t, "role", None) or "").lower()
            body = (getattr(t, "text", None) or "").strip()
            if role in {"", "candidate"} and body:
                parts.append(body)
    return " ".join(parts)


def score_voice_analysis(
    *,
    features: dict[str, Any],
    transcript_text: str | None = None,
    transcript_turns: list[Any] | None = None,
    wpm_target_low: float = 110.0,
    wpm_target_high: float = 160.0,
) -> dict[str, Any]:
    """Return structured speech_patterns, delivery, confidence_indicators."""
    limitations = [
        "Voice analysis reports speech patterns and delivery cues only — "
        "not emotion, personality, honesty, or hiring suitability.",
    ]

    wpm = _f(features, "words_per_minute")
    silence_pct = _f(features, "silence_percentage", 0.0) or 0.0
    pause_count = int(_f(features, "pause_count", 0.0) or 0)
    long_pauses = int(
        _f(features, "long_pause_count", 0.0)
        or (features.get("pause_stats") or {}).get("long_pause_count")
        or 0
    )
    speech_dur = _f(features, "speech_duration_seconds", 0.0) or 0.0
    rms_mean = _f(features, "rms_energy_mean")
    rms_std = _f(features, "rms_energy_std")
    pitch_available = bool(features.get("pitch_available"))
    pitch_std = _f(features, "pitch_std_hz")
    clipping = bool(features.get("clipping_detected") or False)

    # --- Speech rate band ---
    if wpm is None:
        rate_band = "unknown"
        rate_score = 0.45
        rate_evidence = ["Speaking rate unavailable (need transcript + speech activity)"]
        limitations.append("words_per_minute missing — rate scored neutrally")
    elif wpm < 80:
        rate_band = "slow"
        rate_score = 0.45
        rate_evidence = [f"WPM={wpm:.1f} (below typical interview pace)"]
    elif wpm < wpm_target_low:
        rate_band = "measured"
        rate_score = 0.7
        rate_evidence = [f"WPM={wpm:.1f} (slightly measured)"]
    elif wpm <= wpm_target_high:
        rate_band = "balanced"
        rate_score = 0.9
        rate_evidence = [f"WPM={wpm:.1f} (within {wpm_target_low:.0f}–{wpm_target_high:.0f})"]
    elif wpm <= 190:
        rate_band = "fast"
        rate_score = 0.65
        rate_evidence = [f"WPM={wpm:.1f} (brisk)"]
    else:
        rate_band = "rushed"
        rate_score = 0.4
        rate_evidence = [f"WPM={wpm:.1f} (rushed)"]

    # --- Pause pattern ---
    if silence_pct < 5:
        pause_band = "minimal_pauses"
        pause_score = 0.55
    elif silence_pct <= 35:
        pause_band = "natural_pauses"
        pause_score = 0.88
    elif silence_pct <= 50:
        pause_band = "frequent_pauses"
        pause_score = 0.55
    else:
        pause_band = "heavy_silence"
        pause_score = 0.35
    if long_pauses >= 3:
        pause_score = _clamp01(pause_score - 0.12)
    pause_evidence = [
        f"Silence {silence_pct:.1f}%",
        f"Pauses={pause_count}, long_pauses={long_pauses}",
    ]

    # --- Fluency (speech activity continuity) ---
    if speech_dur <= 0.2:
        fluency = 0.2
        fluency_evidence = ["Very little speech-active audio"]
    else:
        fluency = _clamp01(
            0.35 * rate_score + 0.45 * pause_score + (0.2 if pause_count <= 12 else 0.05)
        )
        fluency_evidence = [f"Speech-active duration={speech_dur:.2f}s"]

    speech_patterns = {
        "speaking_rate_band": rate_band,
        "speaking_rate_score": round(rate_score, 3),
        "words_per_minute": wpm,
        "pause_pattern": pause_band,
        "pause_score": round(pause_score, 3),
        "fluency_score": round(fluency, 3),
        "evidence": rate_evidence + pause_evidence + fluency_evidence,
    }

    # --- Delivery ---
    energy_stability = 0.55
    energy_evidence: list[str] = []
    if rms_mean is not None and rms_std is not None and rms_mean > 1e-6:
        cv = rms_std / rms_mean
        # Moderate variation is OK; extreme instability or near-flat both lower score
        if cv < 0.15:
            energy_stability = 0.7
            energy_evidence.append(f"Stable energy (cv={cv:.2f})")
        elif cv < 0.55:
            energy_stability = 0.85
            energy_evidence.append(f"Natural energy variation (cv={cv:.2f})")
        else:
            energy_stability = 0.5
            energy_evidence.append(f"High energy variation (cv={cv:.2f})")
    else:
        energy_evidence.append("RMS energy unavailable")
        limitations.append("Energy stability scored neutrally")

    if clipping:
        energy_stability = _clamp01(energy_stability - 0.15)
        energy_evidence.append("Clipping detected — delivery quality reduced")

    pitch_stability = 0.55
    pitch_evidence: list[str] = []
    if pitch_available and pitch_std is not None:
        # Mild pitch variation is expected; extreme std may indicate noise
        if pitch_std < 15:
            pitch_stability = 0.75
            pitch_evidence.append(f"Pitch std={pitch_std:.1f} Hz (steady)")
        elif pitch_std < 45:
            pitch_stability = 0.8
            pitch_evidence.append(f"Pitch std={pitch_std:.1f} Hz (natural)")
        else:
            pitch_stability = 0.55
            pitch_evidence.append(f"Pitch std={pitch_std:.1f} Hz (high variability)")
    else:
        pitch_evidence.append("Pitch unavailable — not used against the candidate")
        limitations.append("Pitch metrics unavailable or unreliable")

    delivery_score = _clamp01(
        0.4 * rate_score + 0.3 * pause_score + 0.2 * energy_stability + 0.1 * pitch_stability
    )
    delivery_gaps: list[str] = []
    if rate_band in {"rushed", "slow"}:
        delivery_gaps.append("Aim for a steadier speaking pace")
    if pause_band in {"heavy_silence", "frequent_pauses"}:
        delivery_gaps.append("Reduce long silences; keep answers more continuous")
    if pause_band == "minimal_pauses" and rate_band in {"fast", "rushed"}:
        delivery_gaps.append("Add brief pauses between points for clarity")
    if clipping:
        delivery_gaps.append("Reduce input gain / avoid clipping")

    delivery = {
        "score": round(delivery_score, 3),
        "pacing_score": round(rate_score, 3),
        "silence_management_score": round(pause_score, 3),
        "energy_stability_score": round(energy_stability, 3),
        "pitch_stability_score": round(pitch_stability, 3),
        "evidence": energy_evidence + pitch_evidence + rate_evidence[:1],
        "gaps": delivery_gaps[:4],
    }

    # --- Confidence indicators (linguistic + acoustic proxies; not ground-truth confidence) ---
    blob = _transcript_blob(transcript_text, transcript_turns)
    lower = blob.lower()
    words = re.findall(r"\w+", lower)
    hedges = sum(1 for h in _HEDGE if h in lower)
    fillers = sum(1 for f in _FILLER if f in lower)
    asserts = sum(1 for a in _ASSERT if a in lower)
    word_n = len(words)

    linguistic = 0.5
    ling_cues: list[str] = []
    if word_n == 0:
        ling_cues.append("No transcript — linguistic confidence cues unavailable")
        limitations.append("Linguistic confidence cues require transcript text")
        linguistic = 0.45
    else:
        linguistic = _clamp01(
            0.55
            + 0.08 * min(asserts, 3)
            - 0.06 * min(hedges, 4)
            - 0.05 * min(fillers, 5)
            + (0.08 if word_n >= 25 else -0.05)
        )
        ling_cues.append(f"Hedges={hedges}, fillers={fillers}, assertive cues={asserts}")
        if hedges + fillers >= 4:
            ling_cues.append("Frequent hedge/filler phrases in transcript")
        if asserts >= 2:
            ling_cues.append("Concrete / ownership-style phrasing present")

    acoustic_conf = _clamp01(0.35 * delivery_score + 0.35 * fluency + 0.3 * energy_stability)
    acoustic_cues = [
        f"Delivery score={delivery_score:.2f}",
        f"Fluency score={fluency:.2f}",
    ]

    conf_score = _clamp01(0.55 * linguistic + 0.45 * acoustic_conf)
    if conf_score >= 0.75:
        band = "high"
    elif conf_score >= 0.55:
        band = "medium"
    else:
        band = "low"

    confidence_indicators = {
        "score": round(conf_score, 3),
        "band": band,
        "linguistic_score": round(linguistic, 3),
        "acoustic_score": round(acoustic_conf, 3),
        "linguistic_cues": ling_cues,
        "acoustic_cues": acoustic_cues,
        "note": (
            "Indicator of speech assertiveness/fluency patterns — "
            "not a validated psychological confidence measure."
        ),
    }

    overall = _clamp01(0.5 * delivery_score + 0.3 * fluency + 0.2 * conf_score)
    strengths: list[str] = []
    improvements: list[str] = list(delivery_gaps)
    if rate_band == "balanced":
        strengths.append("Balanced speaking rate")
    if pause_band == "natural_pauses":
        strengths.append("Natural pause pattern")
    if band == "high":
        strengths.append("Strong fluency/assertiveness indicators")
    if not strengths:
        strengths.append("Baseline speech activity detected" if speech_dur > 0.2 else "Limited speech signal")

    summary = (
        f"Delivery={delivery_score:.2f}, fluency={fluency:.2f}, "
        f"confidence_indicators={conf_score:.2f} ({band}). "
        f"Rate={rate_band}, pauses={pause_band}."
    )

    return {
        "overall_score": round(overall, 3),
        "speech_patterns": speech_patterns,
        "delivery": delivery,
        "confidence_indicators": confidence_indicators,
        "strengths": strengths[:5],
        "improvement_areas": improvements[:5],
        "summary": summary,
        "limitations": limitations,
    }
