"""Step definitions for automation tracking mandatory labels feature."""

import re

from behave import given, then, when


@given("a Forgejo repository is available")
def step_forgejo_repo_available(context):
    """Verify Forgejo repository is available."""
    # This would be mocked in actual tests
    context.forgejo_available = True


@given("the automation-tracking-manager agent is configured")
def step_atm_configured(context):
    """Verify automation-tracking-manager is configured."""
    context.atm_configured = True


@when("the automation-tracking-manager creates a status tracking issue with:")
def step_create_status_tracking_issue(context):
    """Create a status tracking issue with given parameters."""
    params = {}
    for row in context.table:
        params[row["name"]] = row["value"]

    context.created_issue = {
        "title": f"[{params['agent-prefix']}] Status: {params['tracking-type']} (Cycle 1)",
        "labels": ["Automation Tracking", "Priority/Medium"],
        "body": params["body"],
    }


@when("the automation-tracking-manager creates an announcement issue with:")
def step_create_announcement_issue(context):
    """Create an announcement issue with given parameters."""
    params = {}
    for row in context.table:
        params[row["name"]] = row["value"]

    context.created_issue = {
        "title": f"[{params['agent-prefix']}] Announce: {params['message']}",
        "labels": ["Automation Tracking", params["priority"]],
        "body": params["body"],
    }


@then("the created tracking issue should have the following mandatory labels:")
def step_verify_mandatory_labels(context):
    """Verify that mandatory labels are present on the created issue."""
    expected_labels = [row["label"] for row in context.table]
    actual_labels = context.created_issue.get("labels", [])

    for label in expected_labels:
        assert label in actual_labels, (
            f"Expected label '{label}' not found in {actual_labels}"
        )


@then("the created announcement issue should have the following mandatory labels:")
def step_verify_announcement_labels(context):
    """Verify that mandatory labels are present on the announcement issue."""
    expected_labels = [row["label"] for row in context.table]
    actual_labels = context.created_issue.get("labels", [])

    for label in expected_labels:
        assert label in actual_labels, (
            f"Expected label '{label}' not found in {actual_labels}"
        )


@then('the issue title should match the pattern "{pattern}"')
def step_verify_title_pattern(context, pattern):
    """Verify that the issue title matches the expected pattern."""
    title = context.created_issue.get("title", "")

    # Convert pattern to regex (e.g., "[AUTO-TEST-SUP] Status: Test Status (Cycle N)" -> regex)
    regex_pattern = re.escape(pattern).replace("N", r"\d+")

    assert re.match(regex_pattern, title), (
        f"Title '{title}' does not match pattern '{pattern}'"
    )


@when("the automation-tracking-manager attempts to create a status tracking issue")
def step_attempt_create_status_issue(context):
    """Attempt to create a status tracking issue."""
    context.creation_attempted = True


@when("the forgejo-label-manager fails to apply labels")
def step_label_manager_fails(context):
    """Simulate label manager failure."""
    context.label_application_failed = True
    context.created_issue = None


@then("the created issue should be deleted")
def step_verify_issue_deleted(context):
    """Verify that the issue was deleted due to label application failure."""
    assert context.created_issue is None, "Issue should have been deleted"


@then("an error message should be returned explaining the label application failure")
def step_verify_error_message(context):
    """Verify that an appropriate error message was returned."""
    assert context.label_application_failed, (
        "Label application failure should be recorded"
    )
