from pathlib import Path

ROOT = Path(__file__).resolve().parents[3]
CD_WORKFLOW = ROOT / ".gitea" / "workflows" / "cd.yaml"


def _workflow_text() -> str:
    return CD_WORKFLOW.read_text(encoding="utf-8")


def test_post_deploy_pipefail_preserves_smoke_exit_codes() -> None:
    text = _workflow_text()

    assert "set -o pipefail; source /opt/api-venv/bin/activate && python3 scripts/alert_chain_smoke_test.py" in text
    assert "set -o pipefail; source /opt/api-venv/bin/activate && python3 scripts/awooop_source_correlation_apply_smoke.py" in text


def test_post_deploy_critical_gates_exit_nonzero() -> None:
    text = _workflow_text()

    alert_chain_failure = text.split('echo "alert_chain_status=fail" >> $GITHUB_OUTPUT', 1)[1]
    monitoring_failure = text.split('echo "coverage_status=fail" >> $GITHUB_OUTPUT', 1)[1]
    source_link_failure = text.split('echo "source_correlation_apply_status=fail" >> $GITHUB_OUTPUT', 1)[1]

    assert "exit 1" in alert_chain_failure.split("fi", 1)[0]
    assert "exit 1" in monitoring_failure.split("fi", 1)[0]
    assert "exit 1" in source_link_failure.split("fi", 1)[0]


def test_cd_source_link_gate_uses_current_deploy_canary() -> None:
    text = _workflow_text()

    assert "SOURCE_LINK_RUN_REF=\"gitea-cd-${GITHUB_RUN_ID:-manual}-${GITHUB_RUN_ATTEMPT:-1}\"" in text
    assert "export AWOOOP_OPERATOR_API_KEY" in text
    assert "export SOURCE_LINK_CANARY_WORK_ITEM_ID SOURCE_LINK_CANARY_EVENT_ID" in text
    assert "--source-link-canary-target-incident-id INC-20260505-25E744" in text
    assert "--work-item-id \"${SOURCE_LINK_CANARY_WORK_ITEM_ID}\"" in text
    assert "--expected-source-event-provider-event-id \"${SOURCE_LINK_CANARY_EVENT_ID}\"" in text
    assert "codex-sentry-20260513-t15b-v3" not in text
