import os
import time
import wave
import uuid
import logging
from pathlib import Path

logger = logging.getLogger(__name__)

def _dump_pcm16_wav(
    pcm16: bytes,
    *,
    sample_rate: int = 16000,
    channels: int = 1,
    dump_dir: str | None = None,
    prefix: str = "stt",
) -> str | None:
    """
    Salva PCM16LE (raw) em WAV para inspeção.
    Retorna path salvo ou None se desabilitado.
    """
    dump_dir = dump_dir or os.getenv("STT_DUMP_DIR", "")
    if not dump_dir:
        return None

    Path(dump_dir).mkdir(parents=True, exist_ok=True)
    ts = time.strftime("%Y%m%dT%H%M%S")
    fname = f"{prefix}_{ts}_{uuid.uuid4().hex[:8]}.wav"
    path = str(Path(dump_dir) / fname)

    with wave.open(path, "wb") as w:
        w.setnchannels(channels)
        w.setsampwidth(2)  # PCM16 => 2 bytes
        w.setframerate(sample_rate)
        w.writeframes(pcm16)

    return path


def _dump_bytes(path: str, b: bytes) -> None:
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    Path(path).write_bytes(b)

def _dump_audio_for_debug(
    *,
    req_id: str,
    pcm: bytes,
    wav_bytes: bytes,
    sample_rate: int,
    channels: int,
) -> dict:
    """
    Salva PCM e WAV em disco quando STT_DUMP_DIR estiver setado.
    Retorna dict com paths (ou vazio se desabilitado).
    """
    dump_dir = os.getenv("STT_DUMP_DIR", "").strip()
    if not dump_dir:
        return {}

    ts = time.strftime("%Y%m%dT%H%M%S")
    base = str(Path(dump_dir) / f"stt_{ts}_{req_id}")

    pcm_path = base + ".pcm"  # raw PCM16LE
    wav_path = base + ".wav"  # WAV pronto (exatamente o que vai pro STT)

    _dump_bytes(pcm_path, pcm)
    _dump_bytes(wav_path, wav_bytes)

    return {
        "pcm_path": pcm_path,
        "wav_path": wav_path,
        "bytes_pcm": len(pcm),
        "bytes_wav": len(wav_bytes),
        "sample_rate": sample_rate,
        "channels": channels,
    }