"""Tests for the shared get_credentials() function in gitea_auth.py.

These test the credential parsing logic in isolation by mocking subprocess.Popen.
"""
import os
import sys
import unittest
from unittest.mock import MagicMock, patch

sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent.parent))
import gitea_auth  # noqa: E402


class TestGetCredentials(unittest.TestCase):
    """Test the get_credentials function that parses git credential fill output."""

    def setUp(self):
        self.old_env = os.environ.copy()
        os.environ.clear()
        os.environ["GITEA_USE_KEYCHAIN"] = "1"
        self.old_configs = gitea_auth.DYNAMIC_CONFIGS.copy()
        gitea_auth.DYNAMIC_CONFIGS.clear()

    def tearDown(self):
        os.environ.clear()
        os.environ.update(self.old_env)
        gitea_auth.DYNAMIC_CONFIGS.clear()
        gitea_auth.DYNAMIC_CONFIGS.update(self.old_configs)

    def _mock_popen(self, output_text):
        """Create a mock Popen that returns the given text from communicate()."""
        mock_proc = MagicMock()
        mock_proc.communicate.return_value = (output_text, "")
        return mock_proc

    @patch("gitea_auth.subprocess.Popen")
    def test_parses_standard_output(self, mock_popen_cls):
        mock_popen_cls.return_value = self._mock_popen(
            "protocol=https\nhost=gitea.example.com\nusername=admin\npassword=s3cret\n"
        )
        user, password = gitea_auth.get_credentials("gitea.example.com")
        self.assertEqual(user, "admin")
        self.assertEqual(password, "s3cret")

    @patch("gitea_auth.subprocess.Popen")
    def test_handles_password_with_equals(self, mock_popen_cls):
        # Tokens often contain '=' characters
        mock_popen_cls.return_value = self._mock_popen(
            "username=bot\npassword=abc=def=ghi\n"
        )
        user, password = gitea_auth.get_credentials("example.com")
        self.assertEqual(user, "bot")
        self.assertEqual(password, "abc=def=ghi")

    @patch("gitea_auth.subprocess.Popen")
    def test_empty_output_returns_empty(self, mock_popen_cls):
        mock_popen_cls.return_value = self._mock_popen("")
        user, password = gitea_auth.get_credentials("example.com")
        self.assertEqual(user, "")
        self.assertEqual(password, "")

    @patch("gitea_auth.subprocess.Popen")
    def test_missing_password_returns_empty(self, mock_popen_cls):
        mock_popen_cls.return_value = self._mock_popen("username=admin\n")
        user, password = gitea_auth.get_credentials("example.com")
        self.assertEqual(user, "admin")
        self.assertEqual(password, "")

    @patch("gitea_auth.subprocess.Popen")
    def test_sends_correct_stdin(self, mock_popen_cls):
        mock_proc = self._mock_popen("username=u\npassword=p\n")
        mock_popen_cls.return_value = mock_proc

        gitea_auth.get_credentials("gitea.prgs.cc")

        # Verify the correct input was sent to git credential fill
        mock_proc.communicate.assert_called_once_with(
            "protocol=https\nhost=gitea.prgs.cc\n\n"
        )

    def test_loads_credentials_from_env(self):
        os.environ.clear()
        os.environ["GITEA_USER_PRGS"] = "env_user"
        os.environ["GITEA_PASS_PRGS"] = "env_pass"
        user, password = gitea_auth.get_credentials("gitea.prgs.cc")
        self.assertEqual(user, "env_user")
        self.assertEqual(password, "env_pass")

    def test_loads_credentials_from_generic_env(self):
        os.environ.clear()
        os.environ["GITEA_USER"] = "gen_user"
        os.environ["GITEA_PASS"] = "gen_pass"
        user, password = gitea_auth.get_credentials("gitea.example.com")
        self.assertEqual(user, "gen_user")
        self.assertEqual(password, "gen_pass")

    def test_loads_credentials_from_dynamic_configs(self):
        gitea_auth.DYNAMIC_CONFIGS["gitea.example.com"] = {
            "GITEA_USER": "dynamic_user",
            "GITEA_PASS": "dynamic_pass"
        }
        user, password = gitea_auth.get_credentials("gitea.example.com")
        self.assertEqual(user, "dynamic_user")
        self.assertEqual(password, "dynamic_pass")


class TestGetAuthHeader(unittest.TestCase):
    """Test the get_auth_header function."""

    def setUp(self):
        self._saved_env = os.environ.copy()
        self._saved_configs = gitea_auth.DYNAMIC_CONFIGS.copy()
        for key in (
            "GITEA_MCP_CONFIG",
            "GITEA_MCP_PROFILE",
            "GITEA_TOKEN",
            "GITEA_TOKEN_PRGS",
        ):
            os.environ.pop(key, None)
        gitea_auth.DYNAMIC_CONFIGS.clear()

    def tearDown(self):
        os.environ.clear()
        os.environ.update(self._saved_env)
        gitea_auth.DYNAMIC_CONFIGS.clear()
        gitea_auth.DYNAMIC_CONFIGS.update(self._saved_configs)

    @patch("gitea_auth.get_credentials", return_value=("user", "pass"))
    def test_returns_basic_header(self, _cred):
        header = gitea_auth.get_auth_header("example.com")
        self.assertIsNotNone(header)
        self.assertTrue(header.startswith("Basic "))

    @patch("gitea_auth.get_credentials", return_value=("", ""))
    def test_returns_none_for_missing_creds(self, _cred):
        header = gitea_auth.get_auth_header("example.com")
        self.assertIsNone(header)

    def test_returns_token_header_from_env(self):
        with patch.dict(os.environ, {"GITEA_TOKEN_PRGS": "my_prgs_token"}):
            header = gitea_auth.get_auth_header("gitea.prgs.cc")
            self.assertEqual(header, "token my_prgs_token")

    def test_returns_generic_token_header_from_env(self):
        with patch.dict(os.environ, {"GITEA_TOKEN": "generic_token"}):
            header = gitea_auth.get_auth_header("gitea.example.com")
            self.assertEqual(header, "token generic_token")

    def test_returns_token_from_dynamic_configs(self):
        gitea_auth.DYNAMIC_CONFIGS["gitea.example.com"] = {
            "GITEA_TOKEN": "dynamic_token"
        }
        header = gitea_auth.get_auth_header("gitea.example.com")
        self.assertEqual(header, "token dynamic_token")


class TestRepoApiUrl(unittest.TestCase):

    def test_url_format(self):
        url = gitea_auth.repo_api_url("gitea.prgs.cc", "Org", "Repo")
        self.assertEqual(url, "https://gitea.prgs.cc/api/v1/repos/Org/Repo")


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