"""Tests for beta flag collection from native tools."""

from unittest.mock import AsyncMock, MagicMock, patch

import pytest

from nanobot.providers.anthropic_oauth import AnthropicOAuthProvider


@pytest.mark.asyncio
async def test_beta_flags_collected_from_tools():
    """Test that beta flags are extracted from tool objects."""
    provider = AnthropicOAuthProvider(oauth_token="test", thinking_budget=0)

    # Mock tool objects with beta_flag attribute and to_params method
    class MockTool:
        def __init__(self, beta_flag):
            self.beta_flag = beta_flag

        def to_params(self):
            return {"type": "bash_20250124", "name": "bash"}

    tools_with_flags = [
        MockTool("computer-use-2025-11-24"),
        MockTool("computer-use-2025-11-24"),  # Duplicate should be deduplicated
    ]

    # We need to test this via the actual API call flow
    # Mock httpx client
    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "id": "msg_test",
        "type": "message",
        "role": "assistant",
        "content": [{"type": "text", "text": "test"}],
        "model": "claude-opus-4",
        "stop_reason": "end_turn",
        "usage": {"input_tokens": 10, "output_tokens": 10}
    }

    with patch.object(provider, '_client') as mock_client:
        mock_client.post = AsyncMock(return_value=mock_response)

        # Call with messages and tools
        await provider.chat(
            messages=[{"role": "user", "content": "test"}],
            model="claude-opus-4",
            max_tokens=100,
            tools=tools_with_flags
        )

        # Check that beta flag was added to headers (merged with hardcoded flags)
        call_args = mock_client.post.call_args
        headers = call_args[1]["headers"]
        assert "anthropic-beta" in headers
        # Should include hardcoded flags + tool flag, sorted alphabetically
        assert headers["anthropic-beta"] == "claude-code-20250219,computer-use-2025-11-24,context-management-2025-06-27,oauth-2025-04-20"


@pytest.mark.asyncio
async def test_multiple_beta_flags_joined():
    """Test that multiple unique beta flags are joined with commas."""
    provider = AnthropicOAuthProvider(oauth_token="test", thinking_budget=0)

    class MockTool:
        def __init__(self, beta_flag):
            self.beta_flag = beta_flag

        def to_params(self):
            return {"type": "bash_20250124", "name": "bash"}

    tools_with_flags = [
        MockTool("flag-a"),
        MockTool("flag-b"),
    ]

    mock_response = MagicMock()
    mock_response.status_code = 200
    mock_response.json.return_value = {
        "id": "msg_test",
        "type": "message",
        "role": "assistant",
        "content": [{"type": "text", "text": "test"}],
        "model": "claude-opus-4",
        "stop_reason": "end_turn",
        "usage": {"input_tokens": 10, "output_tokens": 10}
    }

    with patch.object(provider, '_client') as mock_client:
        mock_client.post = AsyncMock(return_value=mock_response)

        await provider.chat(
            messages=[{"role": "user", "content": "test"}],
            model="claude-opus-4",
            max_tokens=100,
            tools=tools_with_flags
        )

        call_args = mock_client.post.call_args
        headers = call_args[1]["headers"]
        assert "anthropic-beta" in headers
        # Should include hardcoded flags + tool flags, sorted alphabetically and joined with comma
        assert headers["anthropic-beta"] == "claude-code-20250219,context-management-2025-06-27,flag-a,flag-b,oauth-2025-04-20"
