"""Tests for colony git operations."""

from unittest.mock import patch

import pytest

from fliiq.runtime.colony.git_ops import (
    GitError,
    commit_colony_state,
    create_experiment_branch,
    get_current_branch,
    get_diff_summary,
)
from fliiq.runtime.colony.models import (
    Proposal,
    ProposalType,
    RiskLevel,
    AgentRole,
)


class TestGetCurrentBranch:
    @patch("fliiq.runtime.colony.git_ops._run_git")
    def test_returns_branch(self, mock_git, tmp_path):
        mock_git.return_value.stdout = "main\n"
        assert get_current_branch(tmp_path) == "main"

    @patch("fliiq.runtime.colony.git_ops._run_git")
    def test_strips_whitespace(self, mock_git, tmp_path):
        mock_git.return_value.stdout = "  colony/experiment-001  \n"
        assert get_current_branch(tmp_path) == "colony/experiment-001"


class TestCreateExperimentBranch:
    @patch("fliiq.runtime.colony.git_ops._run_git")
    def test_creates_branch(self, mock_git, tmp_path):
        mock_git.return_value.stdout = "main\n"
        branch = create_experiment_branch(tmp_path, 1)
        assert branch == "colony/experiment-001"
        # Should have called checkout -b
        calls = [str(c) for c in mock_git.call_args_list]
        assert any("checkout" in c and "-b" in c for c in calls)

    @patch("fliiq.runtime.colony.git_ops._run_git")
    def test_experiment_id_formatting(self, mock_git, tmp_path):
        mock_git.return_value.stdout = "main\n"
        assert create_experiment_branch(tmp_path, 42) == "colony/experiment-042"


class TestCommitColonyState:
    @patch("fliiq.runtime.colony.git_ops.subprocess.run")
    @patch("fliiq.runtime.colony.git_ops._run_git")
    def test_nothing_to_commit(self, mock_run_git, mock_subprocess, tmp_path):
        # git diff --cached --quiet returns 0 (nothing staged)
        mock_subprocess.return_value.returncode = 0
        result = commit_colony_state(tmp_path)
        assert result == ""

    @patch("fliiq.runtime.colony.git_ops.subprocess.run")
    @patch("fliiq.runtime.colony.git_ops._run_git")
    def test_commit_changes(self, mock_run_git, mock_subprocess, tmp_path):
        # git diff --cached --quiet returns 1 (something staged)
        mock_subprocess.return_value.returncode = 1
        mock_run_git.return_value.stdout = "abc123def456\n"
        result = commit_colony_state(tmp_path)
        assert result == "abc123def456"


class TestGetDiffSummary:
    @patch("fliiq.runtime.colony.git_ops.subprocess.run")
    def test_returns_diff(self, mock_subprocess, tmp_path):
        mock_subprocess.return_value.stdout = " 3 files changed, 50 insertions(+)\n"
        result = get_diff_summary(tmp_path)
        assert "3 files changed" in result
