"""Tests for .github/workflows/dogfood.yml — validates structure and security."""

from __future__ import annotations

from pathlib import Path

import pytest
import yaml

WORKFLOW_PATH = Path(__file__).resolve().parent.parent / ".github" / "workflows" / "dogfood.yml"


@pytest.fixture(scope="module")
def workflow() -> dict:
    text = WORKFLOW_PATH.read_text(encoding="utf-8")
    parsed = yaml.safe_load(text)
    assert isinstance(parsed, dict)
    return parsed


class TestDogfoodWorkflow:
    """Validate dogfood.yml structure and security."""

    def test_triggers_on_action_yml_change(self, workflow: dict) -> None:
        on_block = workflow.get("on") or workflow.get(True, {})
        push = on_block.get("push", {})
        assert "action.yml" in push.get("paths", [])

    def test_has_pr_trigger(self, workflow: dict) -> None:
        on_block = workflow.get("on") or workflow.get(True, {})
        pr = on_block.get("pull_request", {})
        assert "action.yml" in pr.get("paths", [])

    def test_job_exists(self, workflow: dict) -> None:
        assert "dogfood" in workflow.get("jobs", {})

    def test_permissions_minimal(self, workflow: dict) -> None:
        job = workflow["jobs"]["dogfood"]
        perms = job.get("permissions", {})
        assert perms.get("contents") == "read"
        assert len(perms) == 1, f"Permissions should be minimal: {perms}"

    def test_uses_local_action(self, workflow: dict) -> None:
        job = workflow["jobs"]["dogfood"]
        steps = job.get("steps", [])
        action_steps = [s for s in steps if s.get("uses", "").startswith("./")]
        assert len(action_steps) >= 1, "No step uses: ./ (local action)"

    def test_no_secrets_in_env(self, workflow: dict) -> None:
        raw = WORKFLOW_PATH.read_text(encoding="utf-8")
        assert "secrets." not in raw, "Dogfood workflow should not reference secrets"

    def test_no_api_key_required(self, workflow: dict) -> None:
        raw = WORKFLOW_PATH.read_text(encoding="utf-8")
        assert "CERTISIGMA_API_KEY" not in raw

    def test_uses_checkout(self, workflow: dict) -> None:
        job = workflow["jobs"]["dogfood"]
        steps = job.get("steps", [])
        checkout = [s for s in steps if "checkout" in s.get("uses", "")]
        assert len(checkout) >= 1

    def test_command_is_integrity(self, workflow: dict) -> None:
        job = workflow["jobs"]["dogfood"]
        steps = job.get("steps", [])
        action_step = next(s for s in steps if s.get("uses", "").startswith("./"))
        assert action_step.get("with", {}).get("command") == "integrity"
