# test_aiva_command_bridge.py
import pytest
import pytest_asyncio
import os
import re
import json
from unittest.mock import Mock, patch, MagicMock, AsyncMock
from datetime import datetime
from typing import Dict, List, Optional
import psycopg2
from psycopg2.extras import RealDictCursor
import requests
from pathlib import Path

# ==============================================================================
# FIXTURES
# ==============================================================================

@pytest.fixture(scope="session")
def test_db_config():
    """Test database configuration."""
    return {
        "host": "postgresql-genesis-u50607.vm.elestio.app",
        "port": 25432,
        "user": "postgres",
        "password": "etY0eog17tD-dDuj--IRH",
        "database": "postgres"
    }

@pytest.fixture(scope="function")
def db_connection(test_db_config):
    """Create a fresh database connection for each test."""
    conn = psycopg2.connect(**test_db_config)
    conn.autocommit = False
    
    # Setup schema
    with conn.cursor() as cur:
        cur.execute("CREATE SCHEMA IF NOT EXISTS genesis_bridge")
        cur.execute("""
            CREATE TABLE IF NOT EXISTS genesis_bridge.directives (
                id SERIAL PRIMARY KEY,
                directive_text TEXT NOT NULL,
                priority INTEGER DEFAULT 5,
                status VARCHAR(50) DEFAULT 'pending',
                created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
                confirmed BOOLEAN DEFAULT FALSE,
                metadata JSONB DEFAULT '{}'
            )
        """)
        conn.commit()
    
    yield conn
    
    # Cleanup
    with conn.cursor() as cur:
        cur.execute("TRUNCATE genesis_bridge.directives RESTART IDENTITY")
    conn.commit()
    conn.close()

@pytest.fixture
def telnyx_api_key():
    return "KEY019BE7A3A2D749FCA8681CFF8448A7F0_vTMM1n77CtQxLDT2ra3P1z"

@pytest.fixture
def telnyx_assistant_id():
    return "assistant-696799a5-e994-4ac1-8f26-7b0923aee682"

@pytest.fixture
def mock_telnyx_response():
    return {
        "data": {
            "id": "assistant-696799a5-e994-4ac1-8f26-7b0923aee682",
            "system_prompt": "Original prompt. ",
            "updated_at": "2024-01-01T00:00:00Z"
        }
    }

@pytest.fixture
def sample_directives():
    return {
        "urgent": [
            "Tell Claude to fix the production server immediately",
            "Have Claude deploy the hotfix right now",
            "Claude needs to handle this critical bug ASAP"
        ],
        "high": [
            "Tell Claude this is important",
            "Have Claude review the code soon",
            "High priority task for Claude"
        ],
        "default": [
            "Tell Claude to update the documentation",
            "Have Claude check the logs"
        ],
        "low": [
            "Tell Claude to refactor when possible",
            "Low priority task for Claude, no rush"
        ]
    }

@pytest.fixture
def system_prompt_content():
    """Load the system prompt content for testing."""
    # Simulating the content that should be in the prompt file
    return """
    COMMAND BRIDGE PROTOCOL ADDITION:
    
    When Kinan speaks, detect directive patterns:
    - Keywords: 'tell Claude', 'have Claude', 'directive', 'command', 'task for Claude', 'Claude needs to'
    
    Before relaying:
    1. Confirm the directive back to Kinan
    2. Ask for clarification if unclear
    
    Priority detection:
    - Priority 10: urgent, immediately, right now, critical, ASAP
    - Priority 7: important, soon, high priority  
    - Priority 5: default
    - Priority 3: when possible, low priority, no rush
    
    Tools:
    - Use relay_directive_to_claude for new directives
    - Use check_claude_status for status inquiries
    
    Edge cases:
    - Unclear directives: Ask "Could you clarify what you'd like Claude to do?"
    - Multiple directives: Process sequentially with confirmations
    - Cancellation: "Cancel that" or "Never mind" should abort pending directive
    """

@pytest.fixture
def mock_claude_status():
    return {
        "current_task": "Refactoring database module",
        "status": "in_progress",
        "queue_length": 3,
        "last_completed": "Fixed API endpoint bug"
    }

# ==============================================================================
# UNIT TESTS: Priority Detection Logic
# ==============================================================================

class TestPriorityDetection:
    """Test priority classification logic."""
    
    @pytest.mark.parametrize("phrase,expected_priority", [
        ("fix this immediately", 10),
        ("handle this right now", 10),
        ("critical security patch", 10),
        ("do this ASAP", 10),
        ("urgent: server down", 10),
        ("this is important", 7),
        ("high priority review", 7),
        ("do this soon", 7),
        ("update docs", 5),
        ("check the logs", 5),
        ("default task", 5),
        ("when you have time", 3),
        ("low priority cleanup", 3),
        ("no rush on this", 3),
        ("when possible", 3),
    ])
    def test_extract_priority(self, phrase, expected_priority):
        """Test priority extraction from directive text."""
        def extract_priority(text: str) -> int:
            text_lower = text.lower()
            urgent_keywords = ['urgent', 'immediately', 'right now', 'critical', 'asap']
            high_keywords = ['important', 'soon', 'high priority']
            low_keywords = ['when possible', 'low priority', 'no rush', 'when you have time']
            
            if any(kw in text_lower for kw in urgent_keywords):
                return 10
            elif any(kw in text_lower for kw in high_keywords):
                return 7
            elif any(kw in text_lower for kw in low_keywords):
                return 3
            return 5
        
        assert extract_priority(phrase) == expected_priority

    def test_priority_case_insensitive(self):
        """Ensure priority detection is case insensitive."""
        def extract_priority(text: str) -> int:
            text_lower = text.lower()
            if 'immediately' in text_lower:
                return 10
            return 5
        
        assert extract_priority("Do this IMMEDIATELY") == 10
        assert extract_priority("Do this immediately") == 10
        assert extract_priority("Do This Immediately") == 10

# ==============================================================================
# UNIT TESTS: Directive Recognition
# ==============================================================================

class TestDirectiveRecognition:
    """Test detection of directive intent."""
    
    @pytest.mark.parametrize("utterance,should_trigger", [
        ("Tell Claude to deploy the app", True),
        ("Have Claude review the code", True),
        ("I have a directive for Claude", True),
        ("Command Claude to restart", True),
        ("Task for Claude: fix bug", True),
        ("Claude needs to update the docs", True),
        ("What time is it?", False),
        ("Call mom", False),
        ("What's the weather?", False),
        ("Tell me about Claude", False),
    ])
    def test_directive_keyword_detection(self, utterance, should_trigger):
        """Test that directive keywords are properly detected."""
        directive_patterns = [
            r'tell\s+claude',
            r'have\s+claude',
            r'directive',
            r'command\s+claude',
            r'task\s+for\s+claude',
            r'claude\s+needs\s+to'
        ]
        
        text_lower = utterance.lower()
        is_directive = any(re.search(pattern, text_lower) for pattern in directive_patterns)
        assert is_directive == should_trigger

    def test_multiple_directives_detection(self):
        """Test detection of multiple directives in single utterance."""
        utterance = "Tell Claude to fix the bug and have Claude update the readme"
        # Should detect at least 2 directive patterns
        directive_patterns = [r'tell\s+claude', r'have\s+claude']
        matches = sum(1 for pattern in directive_patterns if re.search(pattern, utterance.lower()))
        assert matches >= 2

# ==============================================================================
# UNIT TESTS: Response Generation
# ==============================================================================

class TestResponseGeneration:
    """Test natural language response generation."""
    
    def test_confirmation_response(self):
        """Test confirmation response formatting."""
        def generate_confirmation(directive: str, priority: int) -> str:
            priority_words = {10: "urgent", 7: "high priority", 5: "standard", 3: "low priority"}
            priority_str = priority_words.get(priority, "standard")
            return f"I'll relay this {priority_str} directive to Claude: {directive}. Should I proceed?"

        response = generate_confirmation("Deploy to production", 10)
        assert "urgent" in response.lower()
        assert "Deploy to production" in response
        assert "Should I proceed" in response

    def test_status_response_natural_language(self, mock_claude_status):
        """Test conversion of status to natural speech."""
        def format_status(status: dict) -> str:
            if status['status'] == 'in_progress':
                return f"Claude is currently working on: {status['current_task']}. " \
                       f"There are {status['queue_length']} tasks in queue. " \
                       f"Last completed: {status['last_completed']}."
            return "Claude is idle."

        response = format_status(mock_claude_status)
        assert "working on: Refactoring database module" in response
        assert "3 tasks in queue" in response
        assert "Fixed API endpoint bug" in response

    def test_clarification_request(self):
        """Test clarification response for unclear directives."""
        def request_clarification() -> str:
            return "I didn't quite catch that. Could you clarify what you'd like Claude to do? For example, say something like 'Tell Claude to fix the login bug' or 'Have Claude review the pull request'."

        response = request_clarification()
        assert "clarify" in response.lower()
        assert "Tell Claude" in response
        assert "Have Claude" in response

# ==============================================================================
# INTEGRATION TESTS: Telnyx API
# ==============================================================================

class TestTelnyxPatchIntegration:
    """Test the Telnyx assistant patching functionality."""
    
    @patch('requests.patch')
    @patch('requests.get')
    def test_fetch_existing_prompt(self, mock_get, mock_patch, telnyx_api_key, telnyx_assistant_id, mock_telnyx_response):
        """Test fetching existing system prompt before patching."""
        mock_get.return_value = Mock(status_code=200, json=lambda: mock_telnyx_response)
        
        headers = {
            "Authorization": f"Bearer {telnyx_api_key}",
            "Content-Type": "application/json"
        }
        
        response = requests.get(
            f"https://api.telnyx.com/v2/ai_assistants/{telnyx_assistant_id}",
            headers=headers
        )
        
        assert response.status_code == 200
        existing_prompt = response.json()['data']['system_prompt']
        assert existing_prompt == "Original prompt. "

    @patch('requests.patch')
    @patch('requests.get')
    def test_append_prompt_patch(self, mock_get, mock_patch, telnyx_api_key, telnyx_assistant_id, 
                                 mock_telnyx_response, system_prompt_content):
        """Test PATCH request appends rather than replaces prompt."""
        mock_get.return_value = Mock(status_code=200, json=lambda: mock_telnyx_response)
        mock_patch.return_value = Mock(status_code=200, json=lambda: {
            "data": {
                "id": telnyx_assistant_id,
                "system_prompt": f"Original prompt. {system_prompt_content}",
                "updated_at": "2024-01-01T00:00:00Z"
            }
        })
        
        # Simulate the patch script logic
        headers = {
            "Authorization": f"Bearer {telnyx_api_key}",
            "Content-Type": "application/json"
        }
        
        # Get existing
        existing = requests.get(
            f"https://api.telnyx.com/v2/ai_assistants/{telnyx_assistant_id}",
            headers=headers
        ).json()
        
        current_prompt = existing['data']['system_prompt']
        new_prompt = current_prompt + "\n\n" + system_prompt_content
        
        # Patch
        response = requests.patch(
            f"https://api.telnyx.com/v2/ai_assistants/{telnyx_assistant_id}",
            headers=headers,
            json={"system_prompt": new_prompt}
        )
        
        assert response.status_code == 200
        assert "COMMAND BRIDGE PROTOCOL" in response.json()['data']['system_prompt']
        assert "Original prompt" in response.json()['data']['system_prompt']

    @patch('requests.patch')
    def test_patch_api_error_handling(self, mock_patch, telnyx_api_key, telnyx_assistant_id):
        """Test handling of API errors during patch."""
        mock_patch.return_value = Mock(
            status_code=401, 
            json=lambda: {"error": "Unauthorized"},
            text='{"error": "Unauthorized"}'
        )
        
        headers = {
            "Authorization": f"Bearer {telnyx_api_key}",
            "Content-Type": "application/json"
        }
        
        response = requests.patch(
            f"https://api.telnyx.com/v2/ai_assistants/{telnyx_assistant_id}",
            headers=headers,
            json={"system_prompt": "test"}
        )
        
        assert response.status_code == 401
        error_data = response.json()
        assert "error" in error_data

# ==============================================================================
# INTEGRATION TESTS: Database Operations
# ==============================================================================

@pytest.mark.integration
class TestDatabaseOperations:
    """Test PostgreSQL integration for directive storage."""
    
    def test_insert_directive(self, db_connection):
        """Test inserting a directive record."""
        with db_connection.cursor() as cur:
            cur.execute("""
                INSERT INTO genesis_bridge.directives (directive_text, priority, status)
                VALUES (%s, %s, %s)
                RETURNING id
            """, ("Deploy to production", 10, "pending"))
            
            result = cur.fetchone()
            db_connection.commit()
            
            assert result[0] is not None

    def test_query_directive_status(self, db_connection):
        """Test querying directive status."""
        with db_connection.cursor(cursor_factory=RealDictCursor) as cur:
            cur.execute("""
                INSERT INTO genesis_bridge.directives (directive_text, priority, status)
                VALUES (%s, %s, %s)
                RETURNING *
            """, ("Fix bug", 7, "confirmed"))
            
            directive = cur.fetchone()
            db_connection.commit()
            
            assert directive['status'] == 'confirmed'
            assert directive['priority'] == 7

    def test_update_directive_status(self, db_connection):
        """Test updating directive status."""
        with db_connection.cursor() as cur:
            cur.execute("""
                INSERT INTO genesis_bridge.directives (directive_text, priority)
                VALUES (%s, %s)
                RETURNING id
            """, ("Test directive", 5))
            
            directive_id = cur.fetchone()[0]
            
            cur.execute("""
                UPDATE genesis_bridge.directives 
                SET status = %s, confirmed = %s
                WHERE id = %s
            """, ("relayed", True, directive_id))
            
            db_connection.commit()
            
            cur.execute("SELECT * FROM genesis_bridge.directives WHERE id = %s", (directive_id,))
            result = cur.fetchone()
            assert result[3] == "relayed"  # status column
            assert result[5] == True  # confirmed column

    def test_directive_queue_ordering(self, db_connection):
        """Test that directives are properly ordered by priority and time."""
        with db_connection.cursor(cursor_factory=RealDictCursor) as cur:
            # Insert mixed priorities
            cur.executemany("""
                INSERT INTO genesis_bridge.directives (directive_text, priority, status)
                VALUES (%s, %s, %s)
            """, [
                ("Low task", 3, "pending"),
                ("Urgent task", 10, "pending"),
                ("Medium task", 5, "pending"),
            ])
            db_connection.commit()
            
            cur.execute("""
                SELECT * FROM genesis_bridge.directives 
                WHERE status = 'pending'
                ORDER BY priority DESC, created_at ASC
            """)
            
            results = cur.fetchall()
            assert results[0]['priority'] == 10
            assert results[1]['priority'] == 5
            assert results[2]['priority'] == 3

# ==============================================================================
# EDGE CASE TESTS
# ==============================================================================

class TestEdgeCases:
    """Test edge cases and error conditions."""
    
    def test_empty_directive_handling(self):
        """Test handling of empty or whitespace-only directives."""
        def validate_directive(text: str) -> bool:
            return text and len(text.strip()) > 0
        
        assert validate_directive("") == False
        assert validate_directive("   ") == False
        assert validate_directive("Valid directive") == True

    def test_cancellation_detection(self):
        """Test detection of cancellation phrases."""
        cancellations = [
            "cancel that",
            "never mind",
            "forget it",
            "scratch that",
            "don't send that"
        ]
        
        def is_cancellation(text: str) -> bool:
            cancel_patterns = ['cancel', 'never mind', 'forget it', 'scratch that', "don't send"]
            return any(pattern in text.lower() for pattern in cancel_patterns)
        
        for phrase in cancellations:
            assert is_cancellation(phrase), f"Failed to detect cancellation: {phrase}"

    def test_sql_injection_prevention(self, db_connection):
        """Test that directive text is properly sanitized."""
        malicious_input = "'; DROP TABLE genesis_bridge.directives; --"
        
        with db_connection.cursor() as cur:
            cur.execute("""
                INSERT INTO genesis_bridge.directives (directive_text, priority)
                VALUES (%s, %s)
            """, (malicious_input, 5))
            db_connection.commit()
            
            # Verify table still exists and contains the text as literal string
            cur.execute("SELECT directive_text FROM genesis_bridge.directives WHERE directive_text = %s", (malicious_input,))
            result = cur.fetchone()
            assert result[0] == malicious_input
            
            cur.execute("SELECT COUNT(*) FROM genesis_bridge.directives")
            count = cur.fetchone()[0]
            assert count >= 1

    def test_very_long_directive(self, db_connection):
        """Test handling of very long directive text."""
        long_text = "A" * 10000
        
        with db_connection.cursor() as cur:
            cur.execute("""
                INSERT INTO genesis_bridge.directives (directive_text, priority)
                VALUES (%s, %s)
            """, (long_text, 5))
            db_connection.commit()
            
            cur.execute("SELECT directive_text FROM genesis_bridge.directives WHERE priority = 5")
            result = cur.fetchone()
            assert len(result[0]) == 10000

    def test_unicode_handling(self, db_connection):
        """Test handling of unicode characters in directives."""
        unicode_text = "Tell Claude to fix the 🐛 bug in the 日本語 module"
        
        with db_connection.cursor() as cur:
            cur.execute("""
                INSERT INTO genesis_bridge.directives (directive_text, priority)
                VALUES (%s, %s)
            """, (unicode_text, 5))
            db_connection.commit()
            
            cur.execute("SELECT directive_text FROM genesis_bridge.directives WHERE priority = 5")
            result = cur.fetchone()
            assert "🐛" in result[0]
            assert "日本語" in result[0]

    def test_concurrent_directive_handling(self, db_connection):
        """Test handling of multiple rapid directives."""
        directives = [
            ("Task 1", 10),
            ("Task 2", 5),
            ("Task 3", 7),
        ]
        
        with db_connection.cursor() as cur:
            cur.executemany("""
                INSERT INTO genesis_bridge.directives (directive_text, priority)
                VALUES (%s, %s)
            """, directives)
            db_connection.commit()
            
            cur.execute("SELECT COUNT(*) FROM genesis_bridge.directives")
            assert cur.fetchone()[0] == 3

# ==============================================================================
# TEST PROMPT CONTENT VALIDATION
# ==============================================================================

class TestSystemPromptContent:
    """Validate the system prompt file content."""
    
    def test_prompt_contains_required_keywords(self, system_prompt_content):
        """Verify all directive keywords are documented."""
        required_keywords = [
            'tell claude',
            'have claude', 
            'directive',
            'command',
            'task for claude',
            'claude needs to'
        ]
        
        content_lower = system_prompt_content.lower()
        for keyword in required_keywords:
            assert keyword in content_lower, f"Missing keyword: {keyword}"

    def test_prompt_contains_priority_levels(self, system_prompt_content):
        """Verify all priority levels are documented."""
        required_priorities = [
            'priority 10',
            'priority 7', 
            'priority 5',
            'priority 3',
            'urgent',
            'immediately',
            'critical',
            'ASAP',
            'important',
            'when possible'
        ]
        
        content_lower = system_prompt_content.lower()
        for priority in required_priorities:
            assert priority.lower() in content_lower, f"Missing priority reference: {priority}"

    def test_prompt_contains_tools(self, system_prompt_content):
        """Verify tool names are documented."""
        assert 'relay_directive_to_claude' in system_prompt_content
        assert 'check_claude_status' in system_prompt_content

    def test_prompt_contains_edge_cases(self, system_prompt_content):
        """Verify edge case handling is documented."""
        edge_case_keywords = [
            'clarification',
            'unclear',
            'multiple directives',
            'cancellation',
            'cancel'
        ]
        
        content_lower = system_prompt_content.lower()
        for keyword in edge_case_keywords:
            assert keyword in content_lower, f"Missing edge case: {keyword}"

    def test_prompt_is_append_not_replace(self, system_prompt_content):
        """Verify prompt is framed as an addition."""
        assert 'ADDITION' in system_prompt_content or 'addition' in system_prompt_content.lower()

# ==============================================================================
# API ENDPOINT TESTS (FastAPI)
# ==============================================================================

class TestFastAPIEndpoints:
    """Test FastAPI endpoints for command bridge."""
    
    @pytest.fixture
    def client(self):
        """Create a test client for FastAPI app."""
        from fastapi.testclient import TestClient
        from fastapi import FastAPI, Header, HTTPException
        import psycopg2
        
        app = FastAPI()
        
        def get_db():
            conn = psycopg2.connect(
                host="postgresql-genesis-u50607.vm.elestio.app",
                port=25432,
                user="postgres",
                password="etY0eog17tD-dDuj--IRH",
                database="postgres"
            )
            try:
                yield conn
            finally:
                conn.close()
        
        def verify_api_key(x_api_key: str = Header(...)):
            if x_api_key != "test-api-key":
                raise HTTPException(status_code=401, detail="Invalid API key")
            return x_api_key
        
        @app.post("/bridge/directive")
        def create_directive(
            directive: dict,
            x_api_key: str = Header(...),
            db=next(get_db())
        ):
            verify_api_key(x_api_key)
            with db.cursor() as cur:
                cur.execute("""
                    INSERT INTO genesis_bridge.directives (directive_text, priority)
                    VALUES (%s, %s)
                    RETURNING id
                """, (directive['text'], directive.get('priority', 5)))
                db.commit()
                return {"id": cur.fetchone()[0], "status": "pending"}
        
        @app.get("/bridge/status")
        def get_status(x_api_key: str = Header(...)):
            verify_api_key(x_api_key)
            return {"claude_status": "idle", "queue_length": 0}
        
        return TestClient(app)

    def test_create_directive_endpoint(self, client):
        """Test POST /bridge/directive."""
        response = client.post(
            "/bridge/directive",
            json={"text": "Test directive", "priority": 10},
            headers={"X-API-Key": "test-api-key"}
        )
        assert response.status_code == 200
        assert "id" in response.json()

    def test_unauthorized_access(self, client):
        """Test that missing API key returns 401."""
        response = client.post(
            "/bridge/directive",
            json={"text": "Test"}
        )
        assert response.status_code == 401

    def test_invalid_api_key(self, client):
        """Test that invalid API key returns 401."""
        response = client.get(
            "/bridge/status",
            headers={"X-API-Key": "wrong-key"}
        )
        assert response.status_code == 401

# ==============================================================================
# CONVERSATION FLOW TESTS
# ==============================================================================

class TestConversationFlows:
    """Test example conversation flows."""
    
    def test_standard_directive_flow(self):
        """Test: Kinan gives directive -> AIVA confirms -> relays."""
        conversation = [
            ("Kinan", "Tell Claude to deploy the app"),
            ("AIVA", "I'll relay this standard directive to Claude: deploy the app. Should I proceed?"),
            ("Kinan", "Yes"),
            ("AIVA", "Relaying to Claude now.")
        ]
        
        # Verify flow structure
        assert "Tell Claude" in conversation[0][1]
        assert "directive" in conversation[1][1].lower()
        assert "relay" in conversation[3][1].lower()

    def test_urgent_directive_flow(self):
        """Test urgent directive with immediate priority."""
        utterance = "Tell Claude to fix the production bug immediately"
        
        # Simulate processing
        def process_directive(text):
            priority = 10 if 'immediately' in text.lower() else 5
            return {
                'text': text.replace('Tell Claude to', '').strip(),
                'priority': priority,
                'confirmed': False
            }
        
        result = process_directive(utterance)
        assert result['priority'] == 10
        assert 'fix the production bug' in result['text']

    def test_status_check_flow(self):
        """Test checking Claude's status."""
        def generate_status_response(claude_state):
            if claude_state['busy']:
                return f"Claude is currently {claude_state['current_task']}. There are {claude_state['queue']} tasks ahead of you."
            return "Claude is available. No tasks in queue."
        
        state = {'busy': True, 'current_task': 'refactoring', 'queue': 2}
        response = generate_status_response(state)
        assert "currently refactoring" in response
        assert "2 tasks ahead" in response

    def test_clarification_flow(self):
        """Test unclear directive requiring clarification."""
        unclear_utterance = "Tell Claude to... um... you know... fix that thing"
        
        def needs_clarification(text):
            vague_words = ['thing', 'stuff', 'um', 'you know']
            return any(word in text.lower() for word in vague_words)
        
        assert needs_clarification(unclear_utterance)
        
        # AIVA should ask for clarification
        clarification_response = "I didn't quite catch that. Could you clarify what you'd like Claude to do?"
        assert "clarify" in clarification_response.lower()

    def test_cancellation_flow(self):
        """Test cancelling a pending directive."""
        conversation = [
            ("Kinan", "Tell Claude to delete the database"),
            ("AIVA", "I'll relay this standard directive to Claude: delete the database. Should I proceed?"),
            ("Kinan", "Wait, cancel that!"),
            ("AIVA", "Cancelled. I won't relay that directive.")
        ]
        
        assert "cancel" in conversation[2][1].lower()
        assert "Cancelled" in conversation[3][1]

    def test_multiple_directives_flow(self):
        """Test handling multiple directives in sequence."""
        directives = [
            "Tell Claude to fix the login bug",
            "Have Claude update the documentation"
        ]
        
        # Should process sequentially
        processed = []
        for d in directives:
            if 'tell claude' in d.lower() or 'have claude' in d.lower():
                processed.append(d)
        
        assert len(processed) == 2
        assert processed[0] == directives[0]
        assert processed[1] == directives[1]

# ==============================================================================
# PERFORMANCE TESTS
# ==============================================================================

class TestPerformance:
    """Basic performance validation."""
    
    def test_directive_insertion_performance(self, db_connection, benchmark):
        """Benchmark directive insertion."""
        def insert_directive():
            with db_connection.cursor() as cur:
                cur.execute("""
                    INSERT INTO genesis_bridge.directives (directive_text, priority)
                    VALUES (%s, %s)
                """, ("Performance test", 5))
                db_connection.commit()
        
        # Run multiple times to get average
        import time
        start = time.time()
        for _ in range(10):
            insert_directive()
        duration = time.time() - start
        
        assert duration < 1.0  # Should complete 10 inserts in under 1 second

# ==============================================================================
# SECURITY TESTS
# ==============================================================================

class TestSecurity:
    """Security validation tests."""
    
    def test_api_key_header_required(self):
        """Verify API key is required in header."""
        # This is tested in the FastAPI section, but adding explicit security test
        pass

    def test_no_sqlite_usage(self):
        """Verify no SQLite imports in codebase."""
        import ast
        import inspect
        
        # Get the test file itself as source
        source = inspect.getsourcefile(TestSecurity)
        with open(source, 'r') as f:
            tree = ast.parse(f.read())
        
        # Check for sqlite imports (should be none in actual implementation)
        # This is a meta-test ensuring the architecture follows PostgreSQL only rule
        for node in ast.walk(tree):
            if isinstance(node, ast.Import):
                for alias in node.names:
                    assert 'sqlite' not in alias.name.lower()

# ==============================================================================
# MAIN ENTRY POINT
# ==============================================================================

if __name__ == "__main__":
    pytest.main([__file__, "-v", "--cov=.", "--cov-report=term-missing"])