import os

import pytest

from terminaluse.lib.environment_variables import EnvironmentVariables
from terminaluse.lib.utils import registration


@pytest.mark.asyncio
async def test_register_agent_does_not_use_env_agent_api_key(monkeypatch):
    """
    Regression test: register_agent() must not send x-agent-api-key for the
    whitelisted /versions/register call. The SDK wrapper reads from
    TERMINALUSE_AGENT_API_KEY when agent_api_key is None, so we force an empty
    key to avoid triggering agent auth.
    """

    class _StubVersions:
        async def register(self, **kwargs):
            return type(
                "_Resp",
                (),
                {
                    "agent_id": "agent_1",
                    "agent_name": "ns/agent",
                    "agent_api_key": "agent_key_123",
                    "branch_id": "branch_1",
                },
            )()

    class _StubClient:
        def __init__(self, **kwargs):
            # If register_agent accidentally passes None, the wrapper would read env.
            assert kwargs.get("agent_api_key") == ""
            assert kwargs.get("token") == ""
            assert kwargs.get("auto_refresh_token") is False
            self.versions = _StubVersions()

    monkeypatch.setenv("TERMINALUSE_AGENT_API_KEY", "should_not_be_used")
    monkeypatch.setattr(registration, "AsyncTerminalUse", _StubClient)

    env_vars = EnvironmentVariables(
        TERMINALUSE_BASE_URL="http://localhost:5003",
        TERMINALUSE_BRANCH_ID="branch_1",
        TERMINALUSE_VERSION_ID="ver_1",
        TERMINALUSE_AGENT_NAME="ns/agent",
        TERMINALUSE_ACP_URL="http://localhost",
        TERMINALUSE_ACP_PORT=8000,
        TERMINALUSE_REGISTRATION_TOKEN=None,
    )

    await registration.register_agent(env_vars)

    assert os.environ["TERMINALUSE_AGENT_ID"] == "agent_1"
    assert os.environ["TERMINALUSE_AGENT_API_KEY"] == "agent_key_123"
