import os
import subprocess
import shutil

import pytest


TOKEN = os.getenv("VOXYGEN_TOKEN")

pytestmark = pytest.mark.skipif(
    not TOKEN,
    reason="Set VOXYGEN_TOKEN env variable to run integration tests",
)


def run_cli(args):
    """
    Runs the installed CLI executable (voxygen-speak).
    """
    cli = shutil.which("voxygen-speak")
    assert cli is not None, "voxygen-speak executable not found in PATH"

    result = subprocess.run(
        [cli, "-t", TOKEN, *args],
        capture_output=True,
        text=True,
    )

    assert result.returncode == 0, result.stderr
    return result


# -------------------------
# Quick start example
# -------------------------

def test_quick_start():
    result = run_cli([
        "-p", "text=Hello world",
        "-p", "voice=Mary",
    ])

    assert "Received response status: 200" in result.stdout


# -------------------------
# Generate audio file
# -------------------------

def test_generate_audio_file(tmp_path):
    input_file = tmp_path / "input.txt"
    input_file.write_text("Hello from pytest!")

    output_file = tmp_path / "output.wav"

    run_cli([
        "-i", str(input_file),
        "-p", "voice=Mary",
        "-o", str(output_file),
    ])

    assert output_file.exists()
    assert output_file.stat().st_size > 1000  # ensure real audio


# -------------------------
# JSON mode
# -------------------------

def test_json_mode():
    result = run_cli([
        "-j",
        "-p", "text=Hello as JSON",
        "-p", "voice=Mary",
    ])

    assert "duration" in result.stdout
    assert "http" in result.stdout


# -------------------------
# /tts/info endpoint
# -------------------------

def test_info_endpoint():
    result = run_cli([
        "https://api.voxygen.fr/tts/info"
    ])

    assert "Response content type:" in result.stdout
    assert "voice" in result.stdout.lower() or "service" in result.stdout.lower()
    