"""Tests for grpc_storage.py AIAUTO_INSECURE=True path.

Covers the untested branch: use_secure=True + AIAUTO_INSECURE=True
(self-signed certificate mode with TOFU cert fetch).
"""

from unittest.mock import MagicMock, patch

FAKE_CERT = b"-----BEGIN CERTIFICATE-----\nfake\n-----END CERTIFICATE-----\n"


class TestPathPrefixGrpcStorageProxyInsecureMode:
    """Test _setup() with AIAUTO_INSECURE=True + use_secure=True."""

    def test_setup_secure_insecure_mode_fetches_cert(self):
        """When use_secure=True and AIAUTO_INSECURE=True, _fetch_server_cert
        is called and its result is passed to ssl_channel_credentials."""
        with patch("aiauto.grpc_storage.grpc") as mock_grpc:
            with patch("aiauto.grpc_storage.AIAUTO_INSECURE", True):
                with patch("aiauto.grpc_storage.create_path_prefix_interceptor") as mock_int:
                    mock_int.return_value = MagicMock(name="interceptor")
                    mock_grpc.insecure_channel.return_value = MagicMock()
                    mock_grpc.secure_channel.return_value = MagicMock()
                    mock_grpc.ssl_channel_credentials.return_value = MagicMock()
                    mock_grpc.intercept_channel.return_value = MagicMock()

                    with patch.dict(
                        "sys.modules",
                        {
                            "optuna.storages._grpc.auto_generated": MagicMock(),
                            "optuna.storages._grpc.auto_generated.api_pb2_grpc": MagicMock(),
                            "optuna.storages._grpc.client": MagicMock(),
                        },
                    ):
                        with patch(
                            "aiauto.grpc_storage.GrpcStorageProxy.__init__", return_value=None
                        ):
                            with patch(
                                "aiauto.core._fetch_server_cert", return_value=FAKE_CERT
                            ) as mock_fetch:
                                from aiauto.grpc_storage import PathPrefixGrpcStorageProxy

                                proxy = PathPrefixGrpcStorageProxy(
                                    host="192.168.1.100",
                                    port=443,
                                    user_id="user123",
                                    use_secure=True,
                                )
                                proxy._host = "192.168.1.100"
                                proxy._port = 443

                                proxy._setup()

                                mock_fetch.assert_called_once_with("192.168.1.100:443")
                                mock_grpc.ssl_channel_credentials.assert_called_once_with(
                                    root_certificates=FAKE_CERT,
                                )
                                call_args = mock_grpc.secure_channel.call_args
                                assert call_args[0][0] == "192.168.1.100:443"
                                options = call_args[1].get(
                                    "options", call_args[0][2] if len(call_args[0]) > 2 else None
                                )
                                assert options is not None
                                assert ("grpc.ssl_target_name_override", "192.168.1.100") in options
