import os
import sys
from pathlib import Path

import pytest
from git import Repo

from conductor.cli.main import main
from tests.cli.cmd.test_files import FIXTURE_DIR


def test_main_no_git(tmpdir) -> None:
    os.chdir(tmpdir)
    with pytest.raises(SystemExit):
        main()


def test_main_with_git_envvars(mocker, monkeypatch) -> None:
    monkeypatch.setenv("CONDUCTOR_GIT_BRANCH", "test-branch")
    monkeypatch.setenv("CONDUCTOR_COMMIT_HASH", "test-commit-hash")
    mocker.patch.object(sys, "argv", ["conductor", "init"])
    init_mock = mocker.patch("conductor.cli.main.init")

    # Should call the init_mock without erroring.
    main()

    init_mock.assert_called()


@pytest.mark.datafiles(Path(FIXTURE_DIR, "pyproject.toml"))
def test_main_init(datafiles, mocker) -> None:
    os.chdir(datafiles)
    repo = Repo.init(datafiles)  # Initialize a git repo in the test directory.
    repo.index.add([str(path) for path in Path(datafiles).iterdir()])
    repo.index.commit("init")

    mocker.patch.object(sys, "argv", ["conductor", "init"])
    init_mock = mocker.patch("conductor.cli.main.init")
    deploy_mock = mocker.patch("conductor.cli.main.deploy")

    main()

    init_mock.assert_called()
    deploy_mock.assert_not_called()
