"""Persist one row per transcription attempt, and meter audio usage.

Follows services/audit_log_service.py's three-layer pattern exactly: a
threadpool hop, a _write that owns its own short-lived SessionLocal and never
raises, and a double-wrap at the public entry point. A logging failure must
never turn into a user-visible error — the user already spoke and is waiting.
"""

import hashlib
import logging
import os

from fastapi.concurrency import run_in_threadpool

from database import SessionLocal
from models.voice_transcription import VoiceTranscription
import services.quota_service as quota_service

logger = logging.getLogger(__name__)

VOICE_STORE_TRANSCRIPT_TEXT = os.getenv("VOICE_STORE_TRANSCRIPT_TEXT", "false").lower() == "true"
VOICE_TOKENS_PER_AUDIO_SECOND = float(os.getenv("VOICE_TOKENS_PER_AUDIO_SECOND", 0))


def text_fingerprint(text: str) -> str:
    """A short hash for correlating logs without ever writing the transcript."""
    return hashlib.sha256((text or "").encode("utf-8")).hexdigest()[:12]


def _write(**fields) -> None:
    db = None
    try:
        db = SessionLocal()
        db.add(VoiceTranscription(**fields))
        db.commit()
    except Exception as e:
        logger.error("Failed to write voice transcription log: %s", e)
        if db is not None:
            try:
                db.rollback()
            except Exception:
                pass
    finally:
        if db is not None:
            try:
                db.close()
            except Exception:
                pass


async def log_attempt(**fields) -> None:
    """Record a transcription attempt. Never raises.

    Failures are recorded too, deliberately: "the ASR was down for 20 minutes"
    is exactly the thing whose absence you cannot distinguish from "logging
    broke".
    """
    try:
        if not VOICE_STORE_TRANSCRIPT_TEXT:
            fields.pop("text", None)
        await run_in_threadpool(_write, **fields)
    except Exception as e:  # double-wrap — see module docstring
        logger.error("voice_log_service.log_attempt failed: %s", e)


def _record_usage_sync(*, user_id, company_id, role_id, audio_seconds: float) -> None:
    tokens = int(round(audio_seconds * VOICE_TOKENS_PER_AUDIO_SECOND))
    if tokens <= 0:
        return
    db = None
    try:
        db = SessionLocal()
        quota_service.record_usage(
            db,
            user_id=user_id,
            company_id=company_id,
            role_id=role_id,
            # conversation_id is a REAL FK on token_usage_logs. An id that is
            # not yet persisted raises IntegrityError, which record_usage
            # swallows into a rollback — losing the usage row silently. None.
            conversation_id=None,
            # Hardcoded, NOT ACTIVE_LLM_PROVIDER: transcription always goes to
            # RACE regardless of which provider serves chat, and copying the
            # usual pattern would mislabel every STT row as "openai".
            provider="race",
            model="whisper",
            source="stt",
            total_tokens=tokens,
            # Always estimated: seconds -> tokens is a policy conversion, not a
            # measurement.
            is_estimated=True,
        )
    except Exception as e:
        logger.warning("Voice usage accounting failed: %s", e)
    finally:
        if db is not None:
            try:
                db.close()
            except Exception:
                pass


async def record_audio_usage(*, user_id, company_id, role_id, audio_seconds: float) -> None:
    """Charge audio against the token quota.

    VOICE_TOKENS_PER_AUDIO_SECOND=0 (the default) means observe-only: skip the
    call entirely rather than writing 0-token rows. Duration still lands in
    voice_transcriptions.audio_seconds, which is where the real data is.
    Collect a week, then set the multiplier from it.
    """
    if VOICE_TOKENS_PER_AUDIO_SECOND <= 0 or not audio_seconds:
        return
    try:
        await run_in_threadpool(
            _record_usage_sync,
            user_id=user_id, company_id=company_id,
            role_id=role_id, audio_seconds=audio_seconds,
        )
    except Exception as e:
        logger.warning("record_audio_usage failed: %s", e)
