from unittest.mock import Mock, patch

import pytest

from k1link.macos_credentials import CredentialDialogError, _dialog_text


@patch("k1link.macos_credentials.platform.system", return_value="Darwin")
@patch("k1link.macos_credentials.shutil.which", return_value="/usr/bin/osascript")
@patch("k1link.macos_credentials.subprocess.run")
def test_dialog_returns_value_without_printing(
    run: Mock,
    _which: Mock,
    _system: Mock,
) -> None:
    run.return_value = Mock(returncode=0, stdout="local-value\n", stderr="")

    assert _dialog_text("Prompt", hidden=True) == "local-value"
    command = run.call_args.args[0]
    assert "local-value" not in command
    assert "with hidden answer" in command[-1]


@patch("k1link.macos_credentials.platform.system", return_value="Darwin")
@patch("k1link.macos_credentials.shutil.which", return_value="/usr/bin/osascript")
@patch("k1link.macos_credentials.subprocess.run")
def test_dialog_cancel_is_not_echoed(
    run: Mock,
    _which: Mock,
    _system: Mock,
) -> None:
    run.return_value = Mock(returncode=1, stdout="", stderr="User canceled.")

    with pytest.raises(CredentialDialogError, match="cancelled"):
        _dialog_text("Prompt", hidden=False)
