"""Tests for branch resolution in `tu tasks create`."""

from __future__ import annotations

from terminaluse.lib.cli.commands import tasks as tasks_cmd
from terminaluse.lib.cli.utils.git_utils import GitInfo


def _git_info(*, branch: str | None, is_git_repo: bool) -> GitInfo:
    return GitInfo(
        branch=branch,
        commit_hash=None,
        commit_message=None,
        is_dirty=False,
        is_git_repo=is_git_repo,
    )


def test_resolve_task_branch_uses_explicit_branch_without_git_lookup(monkeypatch):
    """Explicit --branch should win and skip git detection."""

    def _unexpected_git_lookup():
        raise AssertionError("detect_git_info should not be called when --branch is provided")

    monkeypatch.setattr(tasks_cmd, "detect_git_info", _unexpected_git_lookup)

    branch, source = tasks_cmd._resolve_task_branch("config-a")

    assert branch == "config-a"
    assert source == "flag"


def test_resolve_task_branch_falls_back_to_git_branch(monkeypatch):
    """Without --branch, use current git branch."""
    monkeypatch.setattr(tasks_cmd, "detect_git_info", lambda: _git_info(branch="feature-x", is_git_repo=True))

    branch, source = tasks_cmd._resolve_task_branch(None)

    assert branch == "feature-x"
    assert source == "git"


def test_resolve_task_branch_returns_none_when_no_git_branch(monkeypatch):
    """If no explicit branch and no git branch, leave branch unset."""
    monkeypatch.setattr(tasks_cmd, "detect_git_info", lambda: _git_info(branch=None, is_git_repo=False))

    branch, source = tasks_cmd._resolve_task_branch(None)

    assert branch is None
    assert source == "none"


def test_resolve_task_branch_treats_blank_flag_as_unset(monkeypatch):
    """Blank --branch should be treated as not provided and fall back to git."""
    monkeypatch.setattr(tasks_cmd, "detect_git_info", lambda: _git_info(branch="develop", is_git_repo=True))

    branch, source = tasks_cmd._resolve_task_branch("   ")

    assert branch == "develop"
    assert source == "git"
