import tempfile
import unittest
from pathlib import Path

from avmc.pipeline import CapturePipeline


class TestPipeline(unittest.TestCase):
    def test_subtitle_detection(self):
        self.assertTrue(CapturePipeline._has_subtitle(Path("ABC123C.mp4")))
        self.assertTrue(CapturePipeline._has_subtitle(Path("ABC-123-CHS.mkv")))
        self.assertFalse(CapturePipeline._has_subtitle(Path("ABC-123.mp4")))

    def test_failed_file_stays_when_move_disabled(self):
        with tempfile.TemporaryDirectory() as td:
            base = Path(td)
            video = base / "ABC-123.mp4"
            video.write_bytes(b"video")

            class _Cfg:
                @staticmethod
                def failed_move_enabled():
                    return False

                @staticmethod
                def failed_folder():
                    return str(base / "failed")

            class _Ctx:
                config = _Cfg()
                debug = False

            pipeline = CapturePipeline(_Ctx())
            pipeline._fetch = lambda number: None

            ok, out_dir, fail_path = pipeline._handle_one(video)

            self.assertFalse(ok)
            self.assertIsNone(out_dir)
            self.assertEqual(fail_path, video)
            self.assertTrue(video.exists())
            self.assertFalse((base / "failed").exists())

    def test_failed_file_moves_when_enabled(self):
        with tempfile.TemporaryDirectory() as td:
            base = Path(td)
            video = base / "ABC-123.mp4"
            video.write_bytes(b"video")

            class _Cfg:
                @staticmethod
                def failed_move_enabled():
                    return True

                @staticmethod
                def failed_folder():
                    return str(base / "failed")

            class _Ctx:
                config = _Cfg()
                debug = False

            pipeline = CapturePipeline(_Ctx())
            pipeline._fetch = lambda number: None

            ok, out_dir, fail_path = pipeline._handle_one(video)

            self.assertFalse(ok)
            self.assertIsNone(out_dir)
            self.assertEqual(fail_path, base / "failed" / "ABC-123.mp4")
            self.assertFalse(video.exists())
            self.assertTrue((base / "failed" / "ABC-123.mp4").exists())


if __name__ == "__main__":
    unittest.main()
