"""Voice / ASR routes (HA-499).

Structure follows routers/admin_quota.py — prefix and tags on the APIRouter,
async handlers, response_model declared, structured HTTPException details.

But NOT its dependency: admin_quota gates the whole router on
verify_admin_api_key, a shared static admin key. These are user-facing routes,
so auth is verify_jwt_token + enforce_token_quota, applied PER ROUTE so
/voice/health and /voice/config stay reachable for a quota-exhausted user —
somebody with a dead mic must still be able to diagnose it.
"""

import logging
import os
import time
import uuid

from fastapi import APIRouter, Depends, File, Form, HTTPException, UploadFile
from pydantic import BaseModel

from dependencies import verify_jwt_token, enforce_token_quota
import services.audio_intake as audio_intake
import services.audio_preprocess as audio_preprocess
import services.transcribe_client as transcribe_client
import services.voice_log_service as voice_log_service
import services.voice_rate_limit as voice_rate_limit

logger = logging.getLogger(__name__)

router = APIRouter(prefix="/voice", tags=["voice"])

VOICE_ENABLED = os.getenv("VOICE_ENABLED", "true").lower() == "true"


class TranscribeResponse(BaseModel):
    success: bool
    transcription_id: str
    text: str
    language: str | None = None
    duration_ms: int | None = None
    segments: list = []
    # Present-and-null keeps the client contract stable. Never fabricated:
    # WhisperX's avg_logprob is not a probability, and exponentiating it to
    # look like one would be inventing data.
    confidence: None = None
    preprocessed: bool = False
    timings: dict = {}


def _fail(exc) -> HTTPException:
    """Map an internal error onto an actionable HTTP response.

    Every case gets an error_code so the client can choose wording without
    string-matching, and none of them is a bare 500 — the UI must always be
    able to fall back to "voice unavailable, type instead".
    """
    return HTTPException(
        status_code=exc.status_code,
        detail={"error_code": exc.error_code, "message": exc.detail},
        headers=({"Retry-After": str(exc.retry_after)}
                 if getattr(exc, "retry_after", None) else None),
    )


@router.post("/transcribe", response_model=TranscribeResponse,
             responses={413: {"description": "Audio too large or too long"},
                        415: {"description": "Unsupported audio format"},
                        409: {"description": "Another request is in flight"},
                        429: {"description": "Rate limited"},
                        503: {"description": "Voice service unavailable"}})
async def transcribe_audio(
    file: UploadFile = File(...),
    language: str | None = Form(None),
    agent_voiceprint: str | None = Form(None),
    user_payload: dict = Depends(verify_jwt_token),
    quota: dict = Depends(enforce_token_quota),
):
    """One-shot transcription: record -> upload -> transcribe -> review -> submit.

    Returns text only. The client puts it in the composer for the user to
    review and edit; it is never auto-sent, and it reaches chat history only
    once the user presses send through the normal path.

    Audio is never written to disk outside the per-request temp workspace, and
    never persisted.
    """
    if not VOICE_ENABLED:
        raise HTTPException(503, detail={
            "error_code": "voice_disabled",
            "message": "Voice input is temporarily unavailable."})

    request_id = uuid.uuid4().hex[:12]
    user_id = user_payload.get("user_id")
    company_id = user_payload.get("company_id")
    role_id = user_payload.get("role_id")

    started = time.perf_counter()
    timings = {}
    mime = audio_intake.normalize_mime(file.content_type)

    common = {
        "user_id": user_id, "company_id": company_id, "role_id": role_id,
        "source_mime": mime, "transport": "http",
    }

    try:
        async with voice_rate_limit.single_flight(user_id):
            # ── read (bounded) ────────────────────────────────────────────
            t0 = time.perf_counter()
            payload = await audio_intake.read_capped(file)
            timings["read_ms"] = int((time.perf_counter() - t0) * 1000)

            ffmpeg_ok = audio_preprocess.ffmpeg_available()
            container = audio_intake.validate(file.content_type, payload,
                                              ffmpeg_available=ffmpeg_ok)

            await voice_rate_limit.check_rate_limit(user_id)

            # ── normalize ─────────────────────────────────────────────────
            t0 = time.perf_counter()
            with audio_intake.workspace() as ws:
                prepped = await audio_preprocess.preprocess(
                    payload, ws, audio_intake.extension_for(container, file.content_type))
                timings["preprocess_ms"] = int((time.perf_counter() - t0) * 1000)

                duration_s = prepped["duration_s"]
                if duration_s:
                    await voice_rate_limit.check_rate_limit(user_id, duration_s)

                send_name = "audio.wav" if prepped["preprocessed"] else (
                    f"audio{audio_intake.extension_for(container, file.content_type)}")
                send_type = "audio/wav" if prepped["preprocessed"] else (
                    mime or "application/octet-stream")

                # ── transcribe ────────────────────────────────────────────
                t0 = time.perf_counter()
                async with voice_rate_limit.gpu_slot():
                    result = await transcribe_client.transcribe(
                        prepped["audio"], filename=send_name, content_type=send_type,
                        agent_voiceprint=agent_voiceprint, request_id=request_id)
                timings["asr_ms"] = int((time.perf_counter() - t0) * 1000)

    except (voice_rate_limit.VoiceThrottled, audio_intake.AudioRejected,
            audio_preprocess.PreprocessError, transcribe_client.TranscribeError) as e:
        timings["total_ms"] = int((time.perf_counter() - started) * 1000)
        _log_line(request_id, user_id, len(payload) if 'payload' in dir() else 0,
                  mime, None, None, timings, None, 0, "-", e.error_code)
        await voice_log_service.log_attempt(
            **common, status="rejected", error_code=e.error_code,
            upstream_status=getattr(e, "upstream_status", None),
            total_ms=timings["total_ms"])
        raise _fail(e)

    timings["total_ms"] = int((time.perf_counter() - started) * 1000)

    # Trimming leading silence offsets every segment timestamp, so add it back.
    # duration_ms is reported as the ORIGINAL duration, not the trimmed one.
    offset = prepped.get("trim_offset_s") or 0.0
    segments = result.segments
    if offset:
        for seg in segments:
            if seg.get("start") is not None:
                seg["start"] += offset
            if seg.get("end") is not None:
                seg["end"] += offset

    await voice_log_service.log_attempt(
        **common,
        source_bytes=len(payload), sniffed_container=container,
        audio_seconds=duration_s,
        preprocessed=prepped["preprocessed"], filter_chain=prepped["filter_chain"],
        preprocess_ms=timings.get("preprocess_ms"), asr_ms=timings.get("asr_ms"),
        total_ms=timings["total_ms"],
        language=result.language, char_count=len(result.text),
        segment_count=len(segments), response_shape=result.shape,
        text=result.text, status="success",
    )
    await voice_log_service.record_audio_usage(
        user_id=user_id, company_id=company_id, role_id=role_id,
        audio_seconds=duration_s or 0.0)

    _log_line(request_id, user_id, len(payload), mime, container, duration_s,
              timings, result.language, len(result.text), result.shape, "ok")

    return TranscribeResponse(
        success=True, transcription_id=request_id, text=result.text,
        language=result.language,
        duration_ms=int(duration_s * 1000) if duration_s else None,
        segments=segments, preprocessed=prepped["preprocessed"], timings=timings,
    )


def _log_line(request_id, user_id, nbytes, mime, container, duration, timings,
              language, chars, shape, status) -> None:
    """One structured line per request. Every field non-PII, every field wanted
    during an incident.

    NEVER log the transcript text or the client-supplied filename — the former
    is personal data, the latter is a CRLF log-injection vector.
    """
    logger.info(
        "VOICE | req=%s user=%s bytes=%d mime=%s container=%s dur=%.2fs "
        "preproc_ms=%s asr_ms=%s total_ms=%s lang=%s chars=%d shape=%s status=%s",
        request_id, user_id, nbytes, mime or "-", container or "-", duration or 0.0,
        timings.get("preprocess_ms", "-"), timings.get("asr_ms", "-"),
        timings.get("total_ms", "-"), language or "-", chars, shape, status,
    )


@router.get("/config")
async def voice_config(user_payload: dict = Depends(verify_jwt_token)):
    """Client limits, so the browser can fail fast instead of uploading a file
    the server will reject."""
    return {
        "enabled": VOICE_ENABLED and transcribe_client.is_configured(),
        "max_upload_bytes": audio_intake.VOICE_MAX_UPLOAD_BYTES,
        "max_duration_sec": audio_preprocess.VOICE_MAX_DURATION_SEC,
        "accepted_mimes": sorted(audio_intake.ACCEPTED_MIMES),
        "streaming": False,  # flipped on once WS /voice/stream lands
    }


@router.get("/health")
async def voice_health(user_payload: dict = Depends(verify_jwt_token)):
    """INFORMATIONAL ONLY.

    Do not gate startup on this and do not build a circuit breaker on it: the
    upstream /healthz can report a sub-dependency as unhealthy while
    transcription works perfectly, and a working feature staying dark is worse
    than a red status line.
    """
    asr = await transcribe_client.healthcheck()
    return {
        "enabled": VOICE_ENABLED,
        "asr": asr,
        "ffmpeg": audio_preprocess.status(),
    }
