from pathlib import Path

import yaml

WORKFLOW = Path(".github/workflows/gcp-artifact.yml")


def test_gcp_artifact_workflow_is_manual_only() -> None:
    workflow = yaml.load(WORKFLOW.read_text(), Loader=yaml.BaseLoader)

    assert set(workflow["on"]) == {"workflow_dispatch"}
    assert "push" not in workflow["on"]


def test_gcp_artifact_workflow_requires_main_before_authentication() -> None:
    workflow = WORKFLOW.read_text()

    guard = workflow.index("Require manual main dispatch")
    checkout = workflow.index("actions/checkout@v4")
    auth = workflow.index("google-github-actions/auth@v2")

    assert 'test "${GITHUB_EVENT_NAME}" = "workflow_dispatch"' in workflow
    assert 'test "${GITHUB_REF}" = "refs/heads/main"' in workflow
    assert guard < checkout < auth


def test_gcp_artifact_workflow_retains_immutable_image_digest() -> None:
    workflow = WORKFLOW.read_text()

    assert "gcloud artifacts docker images describe" in workflow
    assert "Image tag already exists; reusing immutable Artifact Registry image." in workflow
    assert 'docker pull "${image_uri}@${image_digest}"' in workflow
    assert 'docker run --rm "${image_uri}@${image_digest}"' in workflow
    assert "docker push" in workflow
    assert "tee docker-push.log" in workflow
    assert "image_digest=" in workflow
    assert "image_ref=" in workflow
    assert "test -n \"${image_digest}\"" in workflow
