import os
import subprocess
import pytest

def test_send_keys_safe_b8_verification(tmp_path):
    """Verify that send_keys_safe for agy sessions goes through submission verification and does not return 0 blindly on failure."""
    # Test script that mocks herdr commands and tests send_keys_safe behavior for agy
    test_script = f"""#!/usr/bin/env bash
set -euo pipefail
SKILL_DIR="{os.path.abspath('.agents/skills')}"
source "$SKILL_DIR/lib.sh"

# Mock _pane_quiescent to succeed
_pane_quiescent() {{ return 0; }}
_pane_dialog_open() {{ return 1; }}

# Mock _sks_herdr commands
_sks_herdr() {{
  if [ "${{1:-}}" = "agent" ] && [ "${{2:-}}" = "prompt" ]; then
    return 1
  fi
  return 0
}}

# Mock _pane_capture to simulate fixed pane content (no execution token, no pane change)
_pane_capture() {{ echo "static content"; }}

# Running send_keys_safe for agy session when submission is NOT accepted
send_keys_safe "test-workspace-creator-agy" "test prompt" "job-123"
"""
    res = subprocess.run(["bash", "-c", test_script], capture_output=True, text=True)
    # Since submission failed after 3 tries (pane static, no token), it must return exit code 4 (not 0)
    assert res.returncode == 4, f"Expected returncode 4 on submission failure for agy, got {res.returncode}. Output: {res.stdout} {res.stderr}"
    assert "Enter not accepted after 3 tries" in res.stderr
