"""Audio upload ingest: bounded read, container sniffing, temp workspace.

Nothing here trusts the client. `content_type` and `filename` are both
attacker-controlled; the magic-byte sniff is what actually decides.
"""

import logging
import os
import shutil
import tempfile
import time
from contextlib import contextmanager

logger = logging.getLogger(__name__)

VOICE_MAX_UPLOAD_BYTES = int(os.getenv("VOICE_MAX_UPLOAD_BYTES", 10 * 1024 * 1024))

_CHUNK = 64 * 1024
_WORKSPACE_PREFIX = "helixta-voice-"

# Containers the browser MediaRecorder actually produces, plus the common
# upload formats. `video/webm` is in here deliberately: Chrome legitimately
# emits it for an audio-only track, and it is the one everybody forgets.
ACCEPTED_MIMES = {
    "audio/webm", "video/webm",
    "audio/ogg", "application/ogg",
    "audio/mp4", "video/mp4", "audio/x-m4a", "audio/m4a",
    "audio/mpeg", "audio/mp3",
    "audio/wav", "audio/x-wav", "audio/wave",
    "audio/flac", "audio/x-flac",
}


# The approved list, as container names rather than MIME types, because the
# decision is made on magic bytes. Kept beside ACCEPTED_MIMES — which is what
# /voice/config advertises to the browser — so the two cannot drift apart
# unnoticed; a test asserts they describe the same set.
ACCEPTED_CONTAINERS = {"wav", "ogg", "webm", "mp4", "flac", "mp3", "aac"}


class AudioRejected(Exception):
    def __init__(self, status_code: int, error_code: str, detail: str):
        self.status_code = status_code
        self.error_code = error_code
        self.detail = detail
        super().__init__(detail)


def sniff_container(head: bytes):
    """Identify the container from magic bytes. Authoritative over content_type.

    Returns a short container name, or None when inconclusive.
    """
    if len(head) < 12:
        return None
    if head[0:4] == b"RIFF" and head[8:12] == b"WAVE":
        return "wav"
    if head[0:4] == b"OggS":
        return "ogg"
    if head[0:4] == b"\x1a\x45\xdf\xa3":  # EBML — webm/mkv
        return "webm"
    if head[4:8] == b"ftyp":
        return "mp4"
    if head[0:4] == b"fLaC":
        return "flac"
    if head[0:3] == b"ID3":
        return "mp3"
    # MPEG audio frame sync: eleven set bits. Matching only \xff\xfb caught one
    # bitrate/layer combination out of many, so plenty of ordinary MP3s sniffed
    # as "unidentified" — which mattered little while unidentified meant "let
    # ffmpeg decide", and matters a great deal now that it means "rejected".
    if head[0] == 0xFF and (head[1] & 0xE0) == 0xE0:
        # Layer bits 00 mark ADTS AAC rather than MPEG layer I/II/III.
        return "aac" if (head[1] & 0x06) == 0 else "mp3"
    return None


def extension_for(container, content_type: str = "") -> str:
    """ffmpeg only needs a hint; the sniff already decided acceptance."""
    if container:
        return {"wav": ".wav", "ogg": ".ogg", "webm": ".webm", "mp4": ".m4a",
                "flac": ".flac", "mp3": ".mp3", "aac": ".aac"}.get(container, ".bin")
    base = (content_type or "").split(";")[0].strip().lower()
    return {"audio/webm": ".webm", "video/webm": ".webm", "audio/ogg": ".ogg",
            "audio/mp4": ".m4a", "audio/mpeg": ".mp3", "audio/wav": ".wav"}.get(base, ".bin")


def normalize_mime(content_type: str) -> str:
    """Strip parameters and lowercase: 'audio/webm;codecs=opus' -> 'audio/webm'."""
    return (content_type or "").split(";")[0].strip().lower()


async def read_capped(upload) -> bytes:
    """Read an UploadFile in chunks, aborting past the byte cap.

    Deliberately NOT `await upload.read()`: there is no ASGI body-size limit in
    this service, so an unbounded read on a large POST is a one-line OOM. The
    cap is enforced as the bytes arrive, not after.
    """
    buf = bytearray()
    while True:
        chunk = await upload.read(_CHUNK)
        if not chunk:
            break
        buf.extend(chunk)
        if len(buf) > VOICE_MAX_UPLOAD_BYTES:
            raise AudioRejected(
                413, "audio_too_large",
                f"That recording is larger than the {VOICE_MAX_UPLOAD_BYTES // (1024 * 1024)} MB limit.",
            )
    if not buf:
        raise AudioRejected(400, "empty_audio", "The recording was empty.")
    return bytes(buf)


def validate(content_type: str, payload: bytes, *, ffmpeg_available: bool):
    """Accept only an APPROVED container, identified from magic bytes.

    An allow-list, not a deny-list, and decided on the bytes rather than on
    `content_type` — the latter is attacker-controlled, so accepting on it
    would defeat the sniff entirely (any payload declaring `audio/wav` would
    sail straight through to the ASR).

    This used to hand anything it could not identify to ffmpeg, on the grounds
    that ffmpeg is the real parser. True, but it left the approved-format list
    advisory: ffmpeg decodes AMR, WMA, AIFF and a video file with an audio
    track, so in practice all of those were accepted. Phase 1 requires the
    approved formats to be ENFORCED, so an unidentifiable payload is now
    refused. Every container a browser records in — webm/EBML, ogg, mp4/ftyp —
    has a signature above, so this costs nothing a real recording relies on.

    `ffmpeg_available` no longer affects acceptance. It is kept because the
    caller has it to hand and it belongs in the log line for a rejection.
    """
    container = sniff_container(payload[:16])
    if container in ACCEPTED_CONTAINERS:
        return container

    logger.info("Rejected audio: container=%s declared=%s bytes=%d ffmpeg=%s",
                container or "unidentified", normalize_mime(content_type),
                len(payload), ffmpeg_available)
    raise AudioRejected(415, "unsupported_audio_type",
                        "That audio format isn't supported. Please record again.")


@contextmanager
def workspace():
    """One temp dir per request, removed in `finally` — that single rmtree is
    the whole cleanup guarantee, and it runs even on a 413 raised mid-read.

    Do NOT switch this to NamedTemporaryFile-with-an-open-handle: on Windows
    (the dev/CI host) ffmpeg cannot open a file another process holds open.
    Write, close, pass the path.
    """
    path = tempfile.mkdtemp(prefix=_WORKSPACE_PREFIX)
    try:
        yield path
    finally:
        shutil.rmtree(path, ignore_errors=True)


def sweep_stale(max_age_seconds: int = 3600) -> int:
    """Remove workspaces a SIGKILL'd worker left behind.

    Without this, recorded voice (PII) leaks onto disk indefinitely whenever a
    worker dies mid-request. Called once at startup.
    """
    root = tempfile.gettempdir()
    now = time.time()
    removed = 0
    try:
        for name in os.listdir(root):
            if not name.startswith(_WORKSPACE_PREFIX):
                continue
            full = os.path.join(root, name)
            try:
                if now - os.path.getmtime(full) > max_age_seconds:
                    shutil.rmtree(full, ignore_errors=True)
                    removed += 1
            except OSError:
                continue
    except OSError as e:
        logger.warning("Voice temp sweep failed: %s", e)
    if removed:
        logger.info("Voice temp sweep removed %d stale workspace(s)", removed)
    return removed
