# test_srt.py — Tests para extraccion SRT con mocks

import os
import sys
import tempfile
import types

from clipkly.core import extraer_srt, sec_to_srt_time


def test_sec_to_srt_time_basico():
    assert sec_to_srt_time(0) == "00:00:00,000"
    assert sec_to_srt_time(1.234) == "00:00:01,234"
    assert sec_to_srt_time(3661.5) == "01:01:01,500"
    print("✅ test_sec_to_srt_time_basico OK")


def test_extraer_srt_mock_model():
    class Segment:
        def __init__(self, start, end, text):
            self.start = start
            self.end = end
            self.text = text

    class Info:
        language = "es"
        language_probability = 0.97

    class FakeWhisperModel:
        def __init__(self, model, device="auto", compute_type="int8"):
            self.model = model
            self.device = device
            self.compute_type = compute_type

        def transcribe(self, video, **kwargs):
            return [
                Segment(0.0, 1.2, "Hola mundo"),
                Segment(1.2, 2.8, "Esto es una prueba"),
            ], Info()

    fake_module = types.SimpleNamespace(WhisperModel=FakeWhisperModel)
    original = sys.modules.get("faster_whisper")
    sys.modules["faster_whisper"] = fake_module

    with tempfile.TemporaryDirectory() as tmpdir:
        video_path = os.path.join(tmpdir, "video.mp4")
        out_path = os.path.join(tmpdir, "video.srt")

        # Solo se valida existencia del archivo fuente en la funcion.
        with open(video_path, "wb") as f:
            f.write(b"fake")

        result = extraer_srt(
            video=video_path,
            out_file=out_path,
            model="small",
            language="es",
            device="cpu",
            compute_type="int8",
            beam_size=3,
            vad_filter=True,
            word_timestamps=False,
        )

        assert os.path.exists(out_path)
        assert result["segments"] == 2
        assert result["language"] == "es"

        with open(out_path, "r", encoding="utf-8") as f:
            content = f.read()

        assert "00:00:00,000 --> 00:00:01,200" in content
        assert "Hola mundo" in content
        assert "Esto es una prueba" in content

    if original is None:
        del sys.modules["faster_whisper"]
    else:
        sys.modules["faster_whisper"] = original

    print("✅ test_extraer_srt_mock_model OK")


if __name__ == "__main__":
    test_sec_to_srt_time_basico()
    test_extraer_srt_mock_model()
    print("\n🎉 Todos los tests de SRT pasaron correctamente!")
