"""Tests for the cloudsense_diagnostics tool."""

import json
from unittest.mock import patch, MagicMock

import pytest

from cloudsense_dx_mcp.tools.diagnostics import execute, _get_sf_cli_version, _human_size


class TestHumanSize:
    def test_bytes(self):
        assert _human_size(500) == "500.0 B"

    def test_kilobytes(self):
        assert _human_size(2048) == "2.0 KB"

    def test_megabytes(self):
        assert _human_size(5 * 1024 * 1024) == "5.0 MB"


class TestGetSfCliVersion:
    def test_returns_version_on_success(self):
        mock = MagicMock(returncode=0, stdout="@salesforce/cli/2.71.4 darwin-arm64\n")
        with patch("cloudsense_dx_mcp.tools.diagnostics.subprocess.run", return_value=mock):
            assert "2.71.4" in _get_sf_cli_version()

    def test_returns_not_installed(self):
        with patch("cloudsense_dx_mcp.tools.diagnostics.subprocess.run",
                    side_effect=FileNotFoundError):
            assert _get_sf_cli_version() == "not installed"


class TestExecute:
    @pytest.mark.asyncio
    async def test_returns_server_info(self):
        with patch("cloudsense_dx_mcp.tools.diagnostics._get_sf_cli_version",
                    return_value="2.71.4"):
            result = json.loads(await execute({"include_recent_logs": False}))
            assert result["success"] is True
            assert "version" in result["server"]
            assert "session_id" in result["server"]
            assert result["sf_cli"]["version"] == "2.71.4"
            assert "logging" in result
            assert "recent_tool_calls" not in result

    @pytest.mark.asyncio
    async def test_includes_recent_logs_by_default(self):
        with patch("cloudsense_dx_mcp.tools.diagnostics._get_sf_cli_version",
                    return_value="2.71.4"):
            result = json.loads(await execute({}))
            assert "recent_tool_calls" in result

    @pytest.mark.asyncio
    async def test_org_connectivity_when_requested(self):
        mock_display = MagicMock(
            returncode=0,
            stdout=json.dumps({"result": {
                "alias": "test-org", "username": "user@test.com",
                "instanceUrl": "https://test.salesforce.com", "apiVersion": "60.0",
            }}),
        )
        with (
            patch("cloudsense_dx_mcp.tools.diagnostics._get_sf_cli_version",
                  return_value="2.71.4"),
            patch("cloudsense_dx_mcp.tools.diagnostics.subprocess.run",
                  return_value=mock_display),
        ):
            result = json.loads(await execute({
                "include_recent_logs": False,
                "check_org_connectivity": True,
            }))
            assert result["org_connectivity"]["reachable"] is True
