"""Tests verifying API keys are never sent in URLs."""

from unittest.mock import AsyncMock, MagicMock, patch

import pytest


class TestDistillerSecurity:
    @pytest.mark.asyncio
    async def test_api_key_not_in_url(self):
        """Distiller must not put API key in URL query string."""
        from neo_cortex.distiller import GeminiDistiller

        mock_client = AsyncMock()
        mock_response = MagicMock()
        mock_response.raise_for_status = MagicMock()
        mock_response.json.return_value = {
            "candidates": [{"content": {"parts": [{"text": "[]"}]}}]
        }
        mock_client.post = AsyncMock(return_value=mock_response)

        distiller = GeminiDistiller.__new__(GeminiDistiller)
        distiller._client = mock_client
        distiller._model = "gemini-2.0-flash"
        distiller._api_key = "test-secret-key"

        await distiller.distill(["Q: test\nA: answer"])

        call_args = mock_client.post.call_args
        url = call_args[0][0] if call_args[0] else call_args.kwargs.get("url", "")
        assert "key=" not in url
        assert "test-secret-key" not in url

    @pytest.mark.asyncio
    async def test_api_key_in_header(self):
        """Distiller must send API key via x-goog-api-key header."""
        from neo_cortex.distiller import GeminiDistiller

        mock_client = AsyncMock()
        mock_response = MagicMock()
        mock_response.raise_for_status = MagicMock()
        mock_response.json.return_value = {
            "candidates": [{"content": {"parts": [{"text": "[]"}]}}]
        }
        mock_client.post = AsyncMock(return_value=mock_response)

        distiller = GeminiDistiller.__new__(GeminiDistiller)
        distiller._client = mock_client
        distiller._model = "gemini-2.0-flash"
        distiller._api_key = "test-secret-key"

        await distiller.distill(["Q: test\nA: answer"])

        call_kwargs = mock_client.post.call_args.kwargs
        headers = call_kwargs.get("headers", {})
        assert headers.get("x-goog-api-key") == "test-secret-key"


class TestLlmSecurity:
    @pytest.mark.asyncio
    async def test_gemini_api_key_not_in_url(self):
        """GeminiClient must not put API key in URL query string."""
        from neo_cortex.llm import GeminiClient

        mock_client = AsyncMock()
        mock_response = MagicMock()
        mock_response.raise_for_status = MagicMock()
        mock_response.json.return_value = {
            "candidates": [{"content": {"parts": [{"text": "result"}]}}]
        }
        mock_client.post = AsyncMock(return_value=mock_response)

        client = GeminiClient.__new__(GeminiClient)
        client._client = mock_client
        client._api_key = "test-secret-key"

        await client.call(prompt="classify:", text="test")

        call_args = mock_client.post.call_args
        url = call_args[0][0] if call_args[0] else call_args.kwargs.get("url", "")
        assert "key=" not in url
        assert "test-secret-key" not in url
