"""
Tests for _try_advance_pr_review_to_decision function.

Replaces the removed _try_advance_pr_review_to_summary tests after
agdt-generate-pr-summary was removed; the workflow now advances
directly to the decision step when all file reviews are complete.
"""

from unittest.mock import patch

import pytest


@pytest.fixture
def mock_state_dir(tmp_path):
    """Fixture to mock the state directory."""
    with patch("agentic_devtools.state.get_state_dir", return_value=tmp_path):
        yield tmp_path


class TestTryAdvancePrReviewToDecision:
    """Tests for _try_advance_pr_review_to_decision function."""

    def test_returns_false_when_no_workflow(self, mock_state_dir):
        """Test returns False when no workflow is active."""
        from agentic_devtools.cli.tasks.commands import _try_advance_pr_review_to_decision

        with patch("agentic_devtools.state.get_workflow_state", return_value=None):
            result = _try_advance_pr_review_to_decision()

        assert result is False

    def test_returns_false_when_wrong_workflow(self, mock_state_dir):
        """Test returns False when workflow is not pull-request-review."""
        from agentic_devtools.cli.tasks.commands import _try_advance_pr_review_to_decision

        with patch(
            "agentic_devtools.state.get_workflow_state",
            return_value={"active": "other-workflow", "step": "file-review"},
        ):
            result = _try_advance_pr_review_to_decision()

        assert result is False

    def test_returns_false_when_wrong_step(self, mock_state_dir):
        """Test returns False when step is not file-review."""
        from agentic_devtools.cli.tasks.commands import _try_advance_pr_review_to_decision

        with patch(
            "agentic_devtools.state.get_workflow_state",
            return_value={"active": "pull-request-review", "step": "decision"},
        ):
            result = _try_advance_pr_review_to_decision()

        assert result is False

    def test_returns_false_when_no_pr_id(self, mock_state_dir):
        """Test returns False when no pull_request_id in state."""
        from agentic_devtools.cli.tasks.commands import _try_advance_pr_review_to_decision
        from agentic_devtools.state import set_value

        set_value("pull_request_id", "")

        with patch(
            "agentic_devtools.state.get_workflow_state",
            return_value={"active": "pull-request-review", "step": "file-review"},
        ):
            result = _try_advance_pr_review_to_decision()

        assert result is False

    def test_returns_false_when_invalid_pr_id(self, mock_state_dir):
        """Test returns False when pull_request_id is not a valid integer."""
        from agentic_devtools.cli.tasks.commands import _try_advance_pr_review_to_decision
        from agentic_devtools.state import set_value

        set_value("pull_request_id", "not-a-number")

        with patch(
            "agentic_devtools.state.get_workflow_state",
            return_value={"active": "pull-request-review", "step": "file-review"},
        ):
            result = _try_advance_pr_review_to_decision()

        assert result is False

    def test_returns_false_when_files_not_complete(self, mock_state_dir):
        """Test returns False when not all files are complete."""
        from agentic_devtools.cli.tasks.commands import _try_advance_pr_review_to_decision
        from agentic_devtools.state import set_value

        set_value("pull_request_id", "12345")

        with (
            patch(
                "agentic_devtools.state.get_workflow_state",
                return_value={"active": "pull-request-review", "step": "file-review"},
            ),
            patch(
                "agentic_devtools.cli.azure_devops.file_review_commands.get_queue_status",
                return_value={"all_complete": False},
            ),
        ):
            result = _try_advance_pr_review_to_decision()

        assert result is False

    def test_advances_to_decision_when_conditions_met(self, mock_state_dir, capsys):
        """Test advances workflow to decision step via advance_workflow_step."""
        from agentic_devtools.cli.tasks.commands import _try_advance_pr_review_to_decision
        from agentic_devtools.state import set_value

        set_value("pull_request_id", "12345")

        with (
            patch(
                "agentic_devtools.state.get_workflow_state",
                return_value={"active": "pull-request-review", "step": "file-review", "context": {}},
            ),
            patch(
                "agentic_devtools.cli.azure_devops.file_review_commands.get_queue_status",
                return_value={
                    "all_complete": True,
                    "completed_count": 3,
                    "pending_count": 0,
                    "total_count": 3,
                },
            ),
            patch(
                "agentic_devtools.cli.workflows.base.advance_workflow_step",
                return_value="rendered prompt",
            ) as mock_advance,
        ):
            result = _try_advance_pr_review_to_decision()

        assert result is True
        mock_advance.assert_called_once_with(
            workflow_name="pull-request-review",
            step_name="decision",
            variables={
                "pull_request_id": "12345",
                "jira_issue_key": "",
                "completed_count": 3,
                "pending_count": 0,
                "total_count": 3,
                "approval_count": 0,
                "changes_count": 0,
            },
            status="in-progress",
        )

        captured = capsys.readouterr()
        assert "ALL FILE REVIEWS COMPLETE" in captured.out

    def test_does_not_start_background_task(self, mock_state_dir):
        """Test that no background task is started (unlike old generate-pr-summary approach)."""
        from agentic_devtools.cli.tasks.commands import _try_advance_pr_review_to_decision
        from agentic_devtools.state import set_value

        set_value("pull_request_id", "12345")

        with (
            patch(
                "agentic_devtools.state.get_workflow_state",
                return_value={"active": "pull-request-review", "step": "file-review", "context": {}},
            ),
            patch(
                "agentic_devtools.cli.azure_devops.file_review_commands.get_queue_status",
                return_value={
                    "all_complete": True,
                    "completed_count": 2,
                    "pending_count": 0,
                    "total_count": 2,
                },
            ),
            patch(
                "agentic_devtools.cli.workflows.base.advance_workflow_step",
                return_value="rendered prompt",
            ),
            patch("agentic_devtools.background_tasks.run_function_in_background") as mock_bg,
        ):
            _try_advance_pr_review_to_decision()

        # No background task should be started
        mock_bg.assert_not_called()

    def test_computes_approval_and_changes_counts_from_review_state(self, mock_state_dir, capsys):
        """Test that approval_count and changes_count are computed from review-state."""
        from unittest.mock import MagicMock

        from agentic_devtools.cli.tasks.commands import _try_advance_pr_review_to_decision
        from agentic_devtools.state import set_value

        set_value("pull_request_id", "12345")

        mock_file_approved = MagicMock()
        mock_file_approved.status = "approved"
        mock_file_needswork = MagicMock()
        mock_file_needswork.status = "needs-work"
        mock_review_state = MagicMock()
        mock_review_state.files = {
            "/src/a.py": mock_file_approved,
            "/src/b.py": mock_file_needswork,
        }

        with (
            patch(
                "agentic_devtools.state.get_workflow_state",
                return_value={"active": "pull-request-review", "step": "file-review", "context": {}},
            ),
            patch(
                "agentic_devtools.cli.azure_devops.file_review_commands.get_queue_status",
                return_value={
                    "all_complete": True,
                    "completed_count": 2,
                    "pending_count": 0,
                    "total_count": 2,
                },
            ),
            patch(
                "agentic_devtools.cli.azure_devops.review_state.load_review_state",
                return_value=mock_review_state,
            ),
            patch(
                "agentic_devtools.cli.workflows.base.advance_workflow_step",
                return_value="rendered prompt",
            ) as mock_advance,
        ):
            result = _try_advance_pr_review_to_decision()

        assert result is True
        call_kwargs = mock_advance.call_args[1]
        assert call_kwargs["variables"]["approval_count"] == 1
        assert call_kwargs["variables"]["changes_count"] == 1
