"""Tests for try advance workflow after commit."""

import pytest

from agentic_devtools import state
from agentic_devtools.cli.workflows import advancement


@pytest.fixture
def clear_state_before(temp_state_dir):
    """Clear state before each test."""
    state_file = temp_state_dir / "state.json"
    if state_file.exists():
        state_file.unlink()
    yield


class TestTryAdvanceWorkflowAfterCommit:
    """Tests for try_advance_workflow_after_commit."""

    def test_no_advance_when_no_workflow(self, temp_state_dir, clear_state_before):
        """Test that nothing happens when no workflow is active."""
        result = advancement.try_advance_workflow_after_commit()
        assert result is False

    def test_no_advance_when_wrong_step(self, temp_state_dir, clear_state_before):
        """Test that nothing happens when not in commit step."""
        state.set_workflow_state(
            name="work-on-jira-issue",
            status="in-progress",
            step="implementation",
        )
        result = advancement.try_advance_workflow_after_commit()
        assert result is False

    def test_advances_from_commit_to_pull_request(self, temp_state_dir, clear_state_before):
        """Test that workflow sets pending transition from commit to pull-request.

        The transition has required_tasks=["agdt-git-commit"], so the actual step
        change is deferred until get_next_workflow_prompt() is called after the task completes.
        """
        state.set_workflow_state(
            name="work-on-jira-issue",
            status="in-progress",
            step="commit",
            context={"jira_issue_key": "PROJECT-1850"},
        )

        result = advancement.try_advance_workflow_after_commit()

        assert result is True
        workflow = state.get_workflow_state()
        # Step remains unchanged until get_next_workflow_prompt is called (has required_tasks)
        assert workflow["step"] == "commit"
        # But pending_transition is set
        assert workflow["context"]["pending_transition"]["to_step"] == "pull-request"

    def test_preserves_branch_name(self, temp_state_dir, clear_state_before):
        """Test that branch name is added to context."""
        state.set_workflow_state(
            name="work-on-jira-issue",
            status="in-progress",
            step="commit",
            context={"jira_issue_key": "PROJECT-1850"},
        )

        advancement.try_advance_workflow_after_commit(branch_name="feature/PROJECT-1850/test")

        workflow = state.get_workflow_state()
        assert workflow["context"]["branch_name"] == "feature/PROJECT-1850/test"
