"""
Module: test_interactive
Description: Tests for interactive-mode guards (guarded_prompt, is_non_interactive).

Implements:
    - docs/cli/reference.md#global-options
    - docs/cli/agent-integration.md#non-interactive-mode
"""

from __future__ import annotations

from unittest.mock import MagicMock, patch

import pytest

from huitzo_cli.interactive import NonInteractiveError, guarded_prompt, is_non_interactive


def _make_ctx(non_interactive: bool | None = None) -> MagicMock:
    """Create a mock typer.Context with the given non_interactive flag."""
    ctx = MagicMock()
    if non_interactive is not None:
        ctx.obj = {"non_interactive": non_interactive}
    else:
        ctx.obj = {}
    return ctx


class TestIsNonInteractive:
    """Test the is_non_interactive() helper."""

    def test_returns_true_when_set(self) -> None:
        ctx = _make_ctx(non_interactive=True)
        assert is_non_interactive(ctx) is True

    def test_returns_false_when_not_set(self) -> None:
        ctx = _make_ctx()
        assert is_non_interactive(ctx) is False

    def test_returns_false_when_explicitly_false(self) -> None:
        ctx = _make_ctx(non_interactive=False)
        assert is_non_interactive(ctx) is False

    def test_returns_false_when_obj_is_none(self) -> None:
        ctx = MagicMock()
        ctx.obj = None
        assert is_non_interactive(ctx) is False


class TestGuardedPrompt:
    """Test guarded_prompt() behavior in both modes."""

    def test_raises_when_non_interactive(self) -> None:
        ctx = _make_ctx(non_interactive=True)
        with pytest.raises(NonInteractiveError, match="non-interactive"):
            guarded_prompt(ctx, "Enter password")

    @patch("huitzo_cli.interactive.typer")
    def test_calls_typer_prompt_when_interactive(self, mock_typer: MagicMock) -> None:
        mock_typer.prompt.return_value = "user_input"
        ctx = _make_ctx(non_interactive=False)

        result = guarded_prompt(ctx, "Enter value")

        mock_typer.prompt.assert_called_once_with("Enter value")
        assert result == "user_input"

    @patch("huitzo_cli.interactive.typer")
    def test_forwards_kwargs_to_prompt(self, mock_typer: MagicMock) -> None:
        mock_typer.prompt.return_value = "secret"
        ctx = _make_ctx(non_interactive=False)

        guarded_prompt(ctx, "Password", hide_input=True)

        mock_typer.prompt.assert_called_once_with("Password", hide_input=True)
