#!/usr/bin/python3
"""Check that Laser's runtime GStreamer and disc-image tools are available.

This test deliberately uses only the dependencies of the laser package itself.
It does not need a CD drive: the encoders are exercised with a short synthetic
audio stream.

Test generated by DeepSeek v4.1 Flash via Debian Inference
"""

import os
import shutil
import sys
import tempfile

import gi

gi.require_version("Gst", "1.0")
from gi.repository import GLib, Gst


REQUIRED_ELEMENTS = [
    # Source used by the ripping pipelines
    "cdparanoiasrc",
    # Elements used by ENC_MAP in src/constants.py
    "avenc_aac",
    "aacparse",
    "mp4mux",
    "flacenc",
    "lamemp3enc",
    "mpegaudioparse",
    "id3mux",
    "opusenc",
    "oggmux",
    "wavenc",
]

REQUIRED_COMMANDS = ["cdrdao", "toc2cue"]

# Synthetic encoding pipelines. These mirror the encoder parts of ENC_MAP
# without requiring a CD drive (audiotestsrc replaces cdparanoiasrc).
ENCODING_PIPELINES = {
    "aac": (
        "audiotestsrc num-buffers=100 wave=sine "
        "! audio/x-raw,rate=44100,channels=2 ! audioconvert "
        "! avenc_aac bitrate=128000 ! aacparse ! mp4mux faststart=true "
        "! filesink location={output}",
        "m4a",
    ),
    "flac": (
        "audiotestsrc num-buffers=100 wave=sine "
        "! audio/x-raw,rate=44100,channels=2 ! audioconvert "
        "! flacenc quality=5 ! filesink location={output}",
        "flac",
    ),
    "mp3": (
        "audiotestsrc num-buffers=100 wave=sine "
        "! audio/x-raw,rate=44100,channels=2 ! audioconvert "
        "! lamemp3enc target=bitrate bitrate=128 ! mpegaudioparse ! id3mux "
        "! filesink location={output}",
        "mp3",
    ),
    "opus": (
        "audiotestsrc num-buffers=100 wave=sine "
        "! audio/x-raw,rate=48000,channels=2 ! audioconvert "
        "! opusenc bitrate=128000 ! oggmux ! filesink location={output}",
        "ogg",
    ),
    "wav": (
        "audiotestsrc num-buffers=100 wave=sine "
        "! audio/x-raw,rate=44100,channels=2 ! audioconvert "
        "! wavenc ! filesink location={output}",
        "wav",
    ),
}


def check_requirements() -> list[str]:
    failures = []

    missing_elements = [
        element
        for element in REQUIRED_ELEMENTS
        if Gst.ElementFactory.find(element) is None
    ]
    if missing_elements:
        failures.append(
            "missing GStreamer element(s): " + ", ".join(missing_elements)
        )

    missing_commands = [
        command for command in REQUIRED_COMMANDS if shutil.which(command) is None
    ]
    if missing_commands:
        failures.append(
            "missing command(s): " + ", ".join(missing_commands)
        )

    return failures


def run_encoding_test(name: str, pipeline_template: str, extension: str) -> list[str]:
    failures = []

    with tempfile.TemporaryDirectory(prefix=f"laser-{name}-") as tmpdir:
        output = os.path.join(tmpdir, f"test.{extension}")
        try:
            pipeline = Gst.parse_launch(
                pipeline_template.format(output=output)
            )
        except GLib.Error as error:
            return [f"{name}: could not build pipeline: {error.message}"]

        pipeline.set_state(Gst.State.PLAYING)
        bus = pipeline.get_bus()
        message = bus.timed_pop_filtered(
            30 * Gst.SECOND, Gst.MessageType.ERROR | Gst.MessageType.EOS
        )
        pipeline.set_state(Gst.State.NULL)

        if message is None:
            failures.append(f"{name}: pipeline timed out")
        elif message.type == Gst.MessageType.ERROR:
            error, debug = message.parse_error()
            failures.append(f"{name}: {error.message} ({debug})")
        elif not os.path.exists(output) or os.path.getsize(output) == 0:
            failures.append(f"{name}: encoder produced no output")

    return failures


def main() -> int:
    Gst.init(None)

    failures = check_requirements()

    # Only run the encoding tests when all required elements are present;
    # otherwise the errors would just repeat the missing-element report.
    if not failures:
        for name, (pipeline, extension) in ENCODING_PIPELINES.items():
            failures.extend(run_encoding_test(name, pipeline, extension))

    if failures:
        for failure in failures:
            print(f"FAIL: {failure}", file=sys.stderr)
        return 1

    print("All required GStreamer elements and disc-image tools are available.")
    return 0


if __name__ == "__main__":
    sys.exit(main())
