import os
import shutil
import sys
from pathlib import Path

import pytest
from git import Repo

from conductor.cli.cmd.deploy import build_image, clean_build
from conductor.internal.utils import exec_sync
from tests.docker.test_files import FIXTURE_DIR


@pytest.mark.skip("Jenkins build image does not have the docker binary currently.")
@pytest.mark.datafiles(Path(FIXTURE_DIR, "test_project"))
def test_build(datafiles):
    whl = list(Path("dist").iterdir())[0]
    whl_dir = Path(datafiles, "wheels_dev")
    whl_dir.mkdir()
    shutil.copy(whl, Path(whl_dir, "twitch_conductor-0.0.1-py3-none-any.whl"))

    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")

    ecr_tag = "test-process-docker-entrypoint"
    sys.path.append(str(datafiles))
    build_dir = clean_build(str(datafiles))
    build_image(ecr_tag, build_dir)

    # Call the container as if from SageMaker Processing, should not error.
    from dags.dag import process_op

    cmd = "docker run "
    conf = process_op.task.config
    for k, v in conf["Environment"].items():
        cmd += f"--env {k}={v} "
    args = conf["AppSpecification"]["ContainerArguments"]
    cmd += f"test-process-docker-entrypoint process {args[0]} {args[1]}"
    exec_sync(cmd)
