"""Step definitions for review playbook validation feature."""

from __future__ import annotations

from pathlib import Path

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


@given('the review playbook file at "{path}"')
def step_given_review_playbook_file(context: Context, path: str) -> None:
    """Store the review playbook file path."""
    context.review_playbook_path = Path(path)


@then("the review playbook file should exist")
def step_then_review_playbook_exists(context: Context) -> None:
    """Verify the review playbook file exists."""
    playbook_path: Path = context.review_playbook_path
    if not playbook_path.exists():
        raise AssertionError(f"Review playbook file not found at {playbook_path}")


@when("I read the review playbook content")
def step_when_read_review_playbook(context: Context) -> None:
    """Read the review playbook file content."""
    playbook_path: Path = context.review_playbook_path
    if not playbook_path.exists():
        raise FileNotFoundError(f"Review playbook file not found at {playbook_path}")
    context.review_playbook_content = playbook_path.read_text(encoding="utf-8")


@then('the playbook should contain the section "{section}"')
def step_then_playbook_contains_section(context: Context, section: str) -> None:
    """Verify the playbook contains a specific section heading."""
    content: str = context.review_playbook_content
    # Section headings in markdown use ## or ### prefix
    if section not in content:
        raise AssertionError(
            f"Section '{section}' not found in review playbook. "
            f"File length: {len(content)} characters"
        )


@then('the playbook should contain the text "{text}"')
def step_then_playbook_contains_text(context: Context, text: str) -> None:
    """Verify the playbook contains specific text."""
    content: str = context.review_playbook_content
    if text not in content:
        raise AssertionError(f"Text '{text}' not found in review playbook")


@then("the playbook should reference these nox sessions:")
def step_then_playbook_references_nox_sessions(context: Context) -> None:
    """Verify the playbook references all required nox sessions."""
    content: str = context.review_playbook_content
    for row in context.table:
        session_name: str = row["session"]
        nox_reference = f"nox -s {session_name}"
        if nox_reference not in content:
            raise AssertionError(
                f"Nox session '{session_name}' (as '{nox_reference}') "
                f"not found in review playbook"
            )
