import logging
from unittest.mock import patch, MagicMock
from click.testing import CliRunner
from browser_history.mcp_server import cli


def test_cli_use_cache_passed_to_make_mcp():
    runner = CliRunner()
    with (
        patch("browser_history.mcp_server.make_mcp") as mock_make_mcp,
        patch("browser_history.mcp_server.load_whitelist", return_value={}),
    ):
        mock_mcp = MagicMock()
        mock_make_mcp.return_value = mock_mcp

        # Test with --use-cache
        result = runner.invoke(cli, ["--use-cache"])

        assert result.exit_code == 0
        # Check if make_mcp was called with use_cache=True
        # We need to see what arguments make_mcp accepts now vs what it will accept
        mock_make_mcp.assert_called_once()
        args, kwargs = mock_make_mcp.call_args
        assert kwargs.get("use_cache") is True


def test_cli_no_cache_passed_to_make_mcp():
    runner = CliRunner()
    with (
        patch("browser_history.mcp_server.make_mcp") as mock_make_mcp,
        patch("browser_history.mcp_server.load_whitelist", return_value={}),
    ):
        mock_mcp = MagicMock()
        mock_make_mcp.return_value = mock_mcp

        # Test with --no-cache
        result = runner.invoke(cli, ["--no-cache"])

        assert result.exit_code == 0
        mock_make_mcp.assert_called_once()
        args, kwargs = mock_make_mcp.call_args
        assert kwargs.get("use_cache") is False


def test_cli_use_cache_passed_to_run_single_query():
    runner = CliRunner()
    with (
        patch("browser_history.mcp_server._run_single_query") as mock_run_query,
        patch("browser_history.mcp_server.load_whitelist", return_value={}),
    ):
        # Test with --use-cache and --query
        result = runner.invoke(cli, ["--use-cache", "--query", "SELECT 1"])

        assert result.exit_code == 0
        mock_run_query.assert_called_once()
        args, kwargs = mock_run_query.call_args
        # kwargs might not be used if passed positionally, but let's check both
        # Actually, looking at the current cli implementation:
        # _run_single_query(sources, max_rows, whitelist, single_query)
        # We want it to be:
        # _run_single_query(sources, max_rows, whitelist, single_query, use_cache=True)
        assert kwargs.get("use_cache") is True
