"""Step definitions for dockerignore scope isolation checks."""

from __future__ import annotations

from pathlib import Path

from behave import given, then, when
from behave.runner import Context


def _dockerignore_patterns(content: str) -> set[str]:
    return {
        line.strip()
        for line in content.splitlines()
        if line.strip() and not line.lstrip().startswith("#")
    }


@given("the repository root for dockerignore validation")
def step_set_project_root(context: Context) -> None:
    context.project_root = Path(__file__).resolve().parents[2]


@then('the dockerignore file "{filename}" should exist')
def step_assert_dockerignore_exists(context: Context, filename: str) -> None:
    dockerignore_path = context.project_root / filename
    assert dockerignore_path.exists(), (
        f"Expected dockerignore file at {dockerignore_path}"
    )


@when('I read the dockerignore file "{filename}"')
def step_read_dockerignore(context: Context, filename: str) -> None:
    dockerignore_path = context.project_root / filename
    assert dockerignore_path.exists(), (
        f"Dockerignore file not found: {dockerignore_path}"
    )
    content = dockerignore_path.read_text(encoding="utf-8")
    context.dockerignore_patterns = _dockerignore_patterns(content)


@then('the dockerignore file should exclude "{pattern}"')
def step_assert_excludes_pattern(context: Context, pattern: str) -> None:
    patterns: set[str] = context.dockerignore_patterns
    assert pattern in patterns, f"Expected dockerignore to exclude {pattern!r}"


@then('the dockerignore file should not exclude "{pattern}"')
def step_assert_does_not_exclude_pattern(context: Context, pattern: str) -> None:
    patterns: set[str] = context.dockerignore_patterns
    assert pattern not in patterns, (
        f"Did not expect dockerignore to exclude {pattern!r}"
    )
