import unittest

from weibo_image_rescue.args import parse_args
from weibo_image_rescue.utils import generate_file_name


class TestArgs(unittest.TestCase):
    def test_update_cdn_conflicts_with_url(self):
        with self.assertRaises(SystemExit):
            parse_args(["-u", "https://wx4.sinaimg.cn/mw690/a.jpg"])

    def test_f_conflicts_with_positional_url(self):
        with self.assertRaises(SystemExit):
            parse_args(["-f", "https://wx4.sinaimg.cn/mw690/a.jpg", "https://x/a.jpg"])

    def test_force_update_flag(self):
        args = parse_args(["--force-update", "https://wx4.sinaimg.cn/mw690/a.jpg"])
        self.assertTrue(args.force_update)
        self.assertEqual(args.image_url, "https://wx4.sinaimg.cn/mw690/a.jpg")

    def test_workers_and_timeout_validation(self):
        with self.assertRaises(SystemExit):
            parse_args(["--workers", "0", "https://wx4.sinaimg.cn/mw690/a.jpg"])
        with self.assertRaises(SystemExit):
            parse_args(["--timeout", "0", "https://wx4.sinaimg.cn/mw690/a.jpg"])

    def test_force_update_requires_positional_url(self):
        with self.assertRaises(SystemExit):
            parse_args(["--force-update"])


class TestGenerateFileName(unittest.TestCase):
    def test_keep_existing_extension(self):
        result = generate_file_name(
            "/path/to/image.jpg",
            "https://wx4.sinaimg.cn/mw690/image.jpg",
            "image/jpeg",
            None,
        )
        self.assertEqual(result, "image.jpg")

    def test_add_extension_when_missing(self):
        result = generate_file_name(
            "/path/to/image",
            "https://wx4.sinaimg.cn/mw690/image",
            "image/jpeg",
            None,
        )
        self.assertEqual(result, "image.jpg")


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