"""Tests for the sidecar_image module and related CLI behaviour."""

import os
import tempfile
import unittest

from video_thumbnail_creator.sidecar_image import detect_sidecar_image


class TestDetectSidecarImage(unittest.TestCase):
    """Tests for detect_sidecar_image()."""

    def test_returns_jpg_when_present(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            video = os.path.join(tmpdir, "myvideo.mp4")
            sidecar = os.path.join(tmpdir, "myvideo.jpg")
            open(video, "w").close()
            open(sidecar, "w").close()
            result = detect_sidecar_image(video)
            self.assertEqual(result, sidecar)

    def test_returns_jpeg_when_present(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            video = os.path.join(tmpdir, "myvideo.mp4")
            sidecar = os.path.join(tmpdir, "myvideo.jpeg")
            open(video, "w").close()
            open(sidecar, "w").close()
            result = detect_sidecar_image(video)
            self.assertEqual(result, sidecar)

    def test_returns_png_when_present(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            video = os.path.join(tmpdir, "myvideo.mp4")
            sidecar = os.path.join(tmpdir, "myvideo.png")
            open(video, "w").close()
            open(sidecar, "w").close()
            result = detect_sidecar_image(video)
            self.assertEqual(result, sidecar)

    def test_returns_tiff_when_present(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            video = os.path.join(tmpdir, "myvideo.mp4")
            sidecar = os.path.join(tmpdir, "myvideo.tiff")
            open(video, "w").close()
            open(sidecar, "w").close()
            result = detect_sidecar_image(video)
            self.assertEqual(result, sidecar)

    def test_returns_tif_when_present(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            video = os.path.join(tmpdir, "myvideo.mp4")
            sidecar = os.path.join(tmpdir, "myvideo.tif")
            open(video, "w").close()
            open(sidecar, "w").close()
            result = detect_sidecar_image(video)
            self.assertEqual(result, sidecar)

    def test_returns_none_when_no_sidecar(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            video = os.path.join(tmpdir, "myvideo.mp4")
            open(video, "w").close()
            result = detect_sidecar_image(video)
            self.assertIsNone(result)

    def test_jpg_takes_priority_over_jpeg(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            video = os.path.join(tmpdir, "myvideo.mp4")
            jpg = os.path.join(tmpdir, "myvideo.jpg")
            jpeg = os.path.join(tmpdir, "myvideo.jpeg")
            open(video, "w").close()
            open(jpg, "w").close()
            open(jpeg, "w").close()
            result = detect_sidecar_image(video)
            self.assertEqual(result, jpg)

    def test_jpg_takes_priority_over_png(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            video = os.path.join(tmpdir, "myvideo.mp4")
            jpg = os.path.join(tmpdir, "myvideo.jpg")
            png = os.path.join(tmpdir, "myvideo.png")
            open(video, "w").close()
            open(jpg, "w").close()
            open(png, "w").close()
            result = detect_sidecar_image(video)
            self.assertEqual(result, jpg)

    def test_ignores_other_extensions(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            video = os.path.join(tmpdir, "myvideo.mp4")
            heic = os.path.join(tmpdir, "myvideo.heic")
            open(video, "w").close()
            open(heic, "w").close()
            result = detect_sidecar_image(video)
            self.assertIsNone(result)

    def test_returns_absolute_path(self):
        with tempfile.TemporaryDirectory() as tmpdir:
            video = os.path.join(tmpdir, "myvideo.mp4")
            sidecar = os.path.join(tmpdir, "myvideo.jpg")
            open(video, "w").close()
            open(sidecar, "w").close()
            result = detect_sidecar_image(video)
            self.assertTrue(os.path.isabs(result))


class TestCLICropPositionArgument(unittest.TestCase):
    """Test that --crop-position is parsed correctly."""

    def _build_parser(self):
        from video_thumbnail_creator.cli import _build_parser
        return _build_parser()

    def test_crop_position_center(self):
        parser = self._build_parser()
        args = parser.parse_args(["extract", "video.mp4", "--crop-position", "center"])
        self.assertEqual(args.crop_position, "center")

    def test_crop_position_left(self):
        parser = self._build_parser()
        args = parser.parse_args(["extract", "video.mp4", "--crop-position", "left"])
        self.assertEqual(args.crop_position, "left")

    def test_crop_position_center_left(self):
        parser = self._build_parser()
        args = parser.parse_args(["extract", "video.mp4", "--crop-position", "center-left"])
        self.assertEqual(args.crop_position, "center-left")

    def test_crop_position_default_is_none(self):
        parser = self._build_parser()
        args = parser.parse_args(["extract", "video.mp4"])
        self.assertIsNone(args.crop_position)

    def test_crop_position_invalid_choice_raises(self):
        parser = self._build_parser()
        with self.assertRaises(SystemExit):
            parser.parse_args(["extract", "video.mp4", "--crop-position", "top"])


class TestCLIRemovedArguments(unittest.TestCase):
    """Test that --claude-api-key and --claude-model have been removed."""

    def _build_parser(self):
        from video_thumbnail_creator.cli import _build_parser
        return _build_parser()

    def test_claude_api_key_not_accepted(self):
        parser = self._build_parser()
        with self.assertRaises(SystemExit):
            parser.parse_args(["extract", "video.mp4", "--claude-api-key", "sk-ant-test"])

    def test_claude_model_not_accepted(self):
        parser = self._build_parser()
        with self.assertRaises(SystemExit):
            parser.parse_args(["extract", "video.mp4", "--claude-model", "claude-3-haiku"])


class TestEmitResultSidecarSource(unittest.TestCase):
    """Test that source='sidecar' is correctly emitted in JSON output."""

    def test_source_sidecar_in_json(self):
        import io
        import json
        from contextlib import redirect_stdout
        from video_thumbnail_creator.cli import _emit_result
        buf = io.StringIO()
        with redirect_stdout(buf):
            _emit_result(
                poster_path="/tmp/p.jpg",
                frame_index=-1,
                mode="auto",
                reasoning="Sidecar image file was used as source.",
                input_path="/tmp/v.mp4",
                use_json=True,
                source="sidecar",
            )
        data = json.loads(buf.getvalue())
        self.assertEqual(data["source"], "sidecar")
        self.assertEqual(data["frame_index"], -1)


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