{% extends '_base.xml.j2' %}

{% block extra_constraints %}
        <rule priority="critical">Do NOT fix failures yourself - route to implement.</rule>
        <rule priority="critical">Check if server is running BEFORE starting one - never spawn duplicates.</rule>
        <rule priority="high">Always close browser session.</rule>
        <rule priority="medium">Take screenshots as evidence.</rule>
{% endblock %}

{% block extra_context %}
        {% include '_project_discovery.xml.j2' %}
{% endblock %}

{% block instructions %}
        {% if not browser_validation_enabled %}
        <phase name="skip_not_available">
            <description>agent-browser tool is not installed globally. Skip this step.</description>
            <update field="step">code-review</update>
            <log>Skipped browser validation: agent-browser not available</log>
        </phase>
        {% else %}
        <phase name="prerequisites">
            <description>Verify prerequisites before browser validation:</description>
            <checks>
                <check>Unit tests passed</check>
                <check>Issue has UI components (check acceptance criteria for: "displays", "shows", "UI", "form", "button", "page", "screen", "navigates", "renders", "visible", "click", "input")</check>
            </checks>
            <fallback>If NO UI components, skip to code-review:
                - Set step to code-review
                - Log: "Skipped browser validation: no UI keywords in acceptance criteria"
                - Exit</fallback>
        </phase>

        <phase name="get_bearings">
            <commands><![CDATA[
pwd
cat .claudesprint/project/current_issue.json
ISSUE_ID=$(cat .claudesprint/project/current_issue.json | jq -r '.issue_id')
claudesprint-tools sprint details "$ISSUE_ID"
            ]]></commands>
        </phase>

        <phase name="discover_dev_server">
            <description>
                Examine the project to determine the dev server URL.
            </description>
            <steps>
                <step>Read package.json, framework config files, .env files</step>
                <step>Identify what framework is being used (Vite, Next.js, NestJS, Django, etc.)</step>
                <step>Determine the likely port from config or framework defaults</step>
                <step>Check .env or .env.local for PORT overrides</step>
            </steps>
            <common_ports>
                <port framework="Vite">5173</port>
                <port framework="Next.js / Nuxt / CRA">3000</port>
                <port framework="Angular">4200</port>
                <port framework="NestJS">3000</port>
                <port framework="Django / FastAPI">8000</port>
                <port framework="Flask">5000</port>
            </common_ports>
            <note>These are defaults - check the actual project config for the real port.</note>
        </phase>

        <phase name="check_or_start_server">
            <description>Check if the dev server is running. If not, start it (checking for duplicates first).</description>
            <note>
                Set DEV_URL and PORT based on your discovery in the previous phase.
                Example: DEV_URL="http://localhost:3000" PORT=3000
            </note>
            <commands><![CDATA[
# Validate required variables are set
if [ -z "$DEV_URL" ] || [ -z "$PORT" ]; then
    echo "ERROR: DEV_URL and PORT must be set before this phase"
    exit 1
fi

# First, check if server is already responding
if curl -s --max-time 5 "$DEV_URL" > /dev/null 2>&1; then
    echo "Server already running at $DEV_URL"
else
    echo "Server not running, checking port..."
    # Check if port is in use (try multiple methods for compatibility)
    if curl -s --max-time 2 "http://localhost:$PORT" > /dev/null 2>&1; then
        echo "Port $PORT responding - server is up"
    elif lsof -i :$PORT > /dev/null 2>&1; then
        echo "Port $PORT is in use but not responding - waiting..."
        sleep 5
    elif ss -tuln 2>/dev/null | grep -q ":$PORT "; then
        echo "Port $PORT is in use (ss) - waiting..."
        sleep 5
    else
        echo "Starting dev server..."
        # Start server in background - use the command discovered from package.json
        # Example: npm run dev &
        # Wait for startup
        sleep 5
    fi
fi
            ]]></commands>
            <important>
                NEVER start a server if one is already running on the same port.
                Check using: curl, lsof, or ss (in that order of preference).
                This prevents duplicate servers that exhaust memory.
            </important>
        </phase>

        <phase name="validate" condition="server is running">
            <description>Perform browser validation if server is running.</description>
            <commands><![CDATA[
agent-browser open "$DEV_URL/<path>"
agent-browser snapshot -i
# Interact as user would based on acceptance criteria
agent-browser fill @e1 "input"
agent-browser click @e2
agent-browser wait --load networkidle
agent-browser screenshot .claude/validation/evidence.png
agent-browser errors
agent-browser close
            ]]></commands>
            <verification>For each UI acceptance criterion verify:</verification>
            <criteria>
                <criterion>Element visible and accessible</criterion>
                <criterion>Interaction works as expected</criterion>
                <criterion>State changes correctly</criterion>
                <criterion>No JavaScript errors</criterion>
            </criteria>
        </phase>

        <phase name="update_current_issue_json_pass" condition="validation passes">
            <update field="step">code-review</update>
            <update field="current_failures">Clear</update>
        </phase>

        <phase name="update_current_issue_json_fail" condition="validation fails">
            <update field="step">implement</update>
            <update field="current_failures">Failure description</update>
            <update field="retry_count">Increment</update>
        </phase>

        <phase name="update_current_issue_json_skip" condition="no UI components OR server not running">
            <update field="step">code-review</update>
            <log>Skipped browser validation: [reason]</log>
        </phase>

        <phase name="log_and_exit">
            <commands><![CDATA[
echo "[$(date -u +%Y-%m-%dT%H:%M:%SZ)] STEP: browser-validation -> <next>" >> .claudesprint/project/current_issue.log
echo "  Result: <PASS/FAIL/SKIP>" >> .claudesprint/project/current_issue.log
            ]]></commands>
        </phase>
        {% endif %}
{% endblock %}

{% block termination %}
        <required>true</required>
        <description>End your response with exactly one of these routing signals:</description>
        <signal value="pass">All UI validations passed</signal>
        <signal value="fail">UI validation failed</signal>
        <signal value="skip">No UI components to validate, server not running, or agent-browser not available</signal>
        <format><![CDATA[<routing_signal>value</routing_signal>]]></format>
{% endblock %}
