from __future__ import annotations

import unittest
from unittest.mock import patch

from r.cli import main, normalize_url


class NormalizeUrlTests(unittest.TestCase):
    def test_keeps_existing_scheme(self) -> None:
        self.assertEqual(normalize_url("https://www.baidu.com"), "https://www.baidu.com")

    def test_adds_https_when_missing_scheme(self) -> None:
        self.assertEqual(normalize_url("www.baidu.com"), "https://www.baidu.com")

    def test_rejects_empty_url(self) -> None:
        with self.assertRaises(ValueError):
            normalize_url("   ")


class MainTests(unittest.TestCase):
    @patch("r.cli.webbrowser.open", return_value=True)
    def test_main_opens_normalized_url(self, mock_open) -> None:
        exit_code = main(["www.baidu.com"])

        self.assertEqual(exit_code, 0)
        mock_open.assert_called_once_with("https://www.baidu.com", new=2)

    @patch("r.cli.webbrowser.open", return_value=False)
    def test_main_returns_error_when_browser_open_fails(self, mock_open) -> None:
        exit_code = main(["https://www.baidu.com"])

        self.assertEqual(exit_code, 1)
        mock_open.assert_called_once_with("https://www.baidu.com", new=2)


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