#!/bin/bash

# Step Pattern Debugger
# Helps identify and fix undefined step patterns

set -e

echo "🔍 BDD Step Pattern Debugger"
echo "================================"
echo ""

if [ $# -eq 0 ]; then
    FEATURE_DIR="features"
else
    FEATURE_DIR=$1
fi

echo "📁 Checking feature files in: $FEATURE_DIR"
echo ""

# Find all feature files
FEATURE_FILES=$(find "$FEATURE_DIR" -name "*.feature" 2>/dev/null)

if [ -z "$FEATURE_FILES" ]; then
    echo "❌ No feature files found in $FEATURE_DIR"
    echo ""
    echo "Usage: $0 <feature_directory>"
    exit 1
fi

echo "📋 Found feature files:"
echo "$FEATURE_FILES" | sed 's/^/  /'
echo ""

# Run Godog to show step definitions
echo "🔧 Current step definitions:"
echo "================================"
godog --format=progress --show-step-definitions "$FEATURE_DIR" 2>&1 || true
echo ""

# Run tests to find undefined steps
echo "⚠️  Undefined steps:"
echo "================================"
TEST_OUTPUT=$(godog --format=progress "$FEATURE_DIR" 2>&1 || true)
echo "$TEST_OUTPUT" | grep -E "undefined|pending|skipped" | sed 's/^/  /' || echo "  None found"
echo ""

# Show suggested patterns
echo "💡 Suggested step implementations:"
echo "================================"
echo "$TEST_OUTPUT" | grep -A 3 "You can implement" | sed 's/^/  /' || echo "  Run 'godog --format=progress' for suggestions"
echo ""

# Check for common issues
echo "🔎 Common issues to check:"
echo "================================"
echo "1. ✅ Step patterns match Godog's EXACT suggestions"
echo "2. ✅ JSON is properly escaped in feature files"
echo "3. ✅ Server is running on port 9191"
echo "4. ✅ Context types are correct (*godog.ScenarioContext)"
echo "5. ✅ Steps are registered in InitializeScenario"
echo ""

# Show example patterns
echo "📖 Example patterns:"
echo "================================"
cat <<'EOF'
# Feature file:
Given the server is running
When I request a greeting for "John"
Then the response should be "{\\"message\\":\\"Hello John!\\"}"

# Step registration (use EXACT patterns from godog output):
ctx.Step(`^the server is running$`, sc.theServerIsRunning)
ctx.Step(`^I request a greeting for "([^"]*)"$`, sc.iRequestAGreetingFor)
ctx.Step(`^the response should be "([^"]*)"$`, sc.theResponseShouldBe)

# Step implementation:
func (sc *StepContext) theServerIsRunning() error {
    return sc.client.Request("GET", "/api/ready", nil)
}

func (sc *StepContext) iRequestAGreetingFor(name string) error {
    return sc.client.Request("GET", fmt.Sprintf("/api/v1/greet/%s", name), nil)
}

func (sc *StepContext) theResponseShouldBe(expected string) error {
    cleanExpected := strings.Trim(expected, `"\`)
    actual := strings.TrimSuffix(string(sc.client.lastBody), "\n")
    if actual != cleanExpected {
        return fmt.Errorf("expected %q, got %q", cleanExpected, actual)
    }
    return nil
}
EOF

echo ""
echo "🎯 Next steps:"
echo "1. Fix undefined steps using Godog's suggested patterns"
echo "2. Verify JSON escaping in feature files"
echo "3. Test server connectivity: curl http://localhost:9191/api/ready"
echo "4. Run full validation: ./scripts/run-bdd-tests.sh"
echo "5. Check debugging guide: .vibe/skills/bdd_testing/references/DEBUGGING.md"
echo ""

echo "📚 Additional resources:"
echo "  • Godog documentation: https://github.com/cucumber/godog"
echo "  • Gherkin reference: https://cucumber.io/docs/gherkin/"
echo "  • BDD best practices: .vibe/skills/bdd_testing/references/BDD_BEST_PRACTICES.md"
echo "  • Test server guide: .vibe/skills/bdd_testing/references/TEST_SERVER.md"
echo "  • Debugging guide: .vibe/skills/bdd_testing/references/DEBUGGING.md"