import pytest

from conductor.cli.cmd.clean import BranchManager
from tests.utils import create_conductor_instance, create_test_project

S3_BUCKET_RESPONSES = {
    "CommonPrefixes": [
        {"Prefix": "test1/"},
        {"Prefix": "test2/"},
        {"Prefix": "test3/"},
        {"Prefix": "closed_test1/"},
        {"Prefix": "closed-test2/"},
    ]
}

MWAA_BUCKET_RESPONSES = {
    "Contents": [
        {"Key": "dags/test-project.test-env.test1.py"},
        {"Key": "dags/test-project.test-env.test2.py"},
        {"Key": "dags/test-project.test-env.test3.py"},
        {"Key": "dags/test-project.test-env.closed_test1.py"},
        {"Key": "dags/test-project.test-env.closed-test2.py"},
    ]
}

IMAGE_ECR_RESPONSE = {
    "imageIds": [
        {"imageDigest": "a1", "imageTag": "main-123"},
        {"imageDigest": "a2", "imageTag": "test1-123"},
        {"imageDigest": "a3", "imageTag": "closed_test1-123"},
        {"imageDigest": "a4", "imageTag": "closed-test2-123"},
        {"imageDigest": "a5", "imageTag": "closed_test3-123"},
    ]
}


@pytest.fixture(autouse=True)
def env_setup(monkeypatch, request):
    if "no_auto_env" in request.keywords:
        return
    monkeypatch.setenv("CONDUCTOR_ENV", "test-env")
    monkeypatch.setenv("CONDUCTOR_GIT_BRANCH", "test-branch")
    monkeypatch.setenv("CONDUCTOR_COMMIT_HASH", "test-commit-hash")
    monkeypatch.setenv("CDK_OUTDIR", "/tmp/test-conductor-cdk")


@pytest.fixture
def basic_project():
    return create_test_project()


@pytest.fixture
def c():
    return create_conductor_instance()


@pytest.fixture
def branch_manager(mocker, request):
    if "dry_run" in request.keywords:
        dry_run = True
    else:
        dry_run = False
    mocker.patch("boto3.client")
    mocker.patch("boto3.resource")
    mocker.patch(
        "conductor.cli.cmd.clean.BranchManager._get_s3_bucket_response",
        side_effect=[S3_BUCKET_RESPONSES, MWAA_BUCKET_RESPONSES],
    )
    mocker.patch(
        "conductor.cli.cmd.clean.BranchManager._get_ecr_response",
        return_value=IMAGE_ECR_RESPONSE,
    )
    mocker.patch("conductor.cli.cmd.clean.BranchManager._prune_remote_branch")
    mocker.patch(
        "conductor.cli.cmd.clean.BranchManager._get_live_branches",
        return_value=["main", "test1", "test2", "test3"],
    )
    s3_deletion_mock = mocker.patch(
        "conductor.cli.cmd.clean.BranchManager._delete_s3_object"
    )
    ecr_deletion_mock = mocker.patch(
        "conductor.cli.cmd.clean.BranchManager._delete_ecr_image"
    )
    return (
        s3_deletion_mock,
        ecr_deletion_mock,
        BranchManager(
            project_root=".",
            s3_bucket="test-project.test-env",
            s3_prefix="",
            airflow_bucket="test-airflow-bucket",
            airflow_prefix="dags/",
            delimiter="/",
            dry_run=dry_run,
        ),
    )
