"""Tests for CLI layer: subprocess bounds, error handling, helpers."""

import os
from unittest.mock import patch, MagicMock

import pytest

from cloudsense_dx_mcp.sfdc.cli import (
    SfCliError,
    _parse_positive_int,
    _run_subprocess,
    get_default_org,
)


class TestParsePositiveInt:
    def test_valid_string(self):
        assert _parse_positive_int("10", 5) == 10

    def test_none_returns_default(self):
        assert _parse_positive_int(None, 8) == 8

    def test_zero_returns_default(self):
        assert _parse_positive_int("0", 8) == 8

    def test_negative_returns_default(self):
        assert _parse_positive_int("-3", 8) == 8

    def test_non_numeric_returns_default(self):
        assert _parse_positive_int("abc", 8) == 8


class TestGetDefaultOrgSfNotFound:
    def test_raises_on_file_not_found(self):
        with patch(
            "cloudsense_dx_mcp.sfdc.cli._run_subprocess",
            side_effect=FileNotFoundError("sf not found"),
        ):
            with pytest.raises(SfCliError, match="not found on PATH"):
                get_default_org()


class TestRunSubprocessSemaphore:
    def test_runs_command_through_semaphore(self):
        with patch("cloudsense_dx_mcp.sfdc.cli.subprocess.run") as mock_run:
            mock_run.return_value = MagicMock(returncode=0, stdout="{}", stderr="")
            result = _run_subprocess(["echo", "test"], timeout=5)
            mock_run.assert_called_once()
            assert result.returncode == 0
