import pytest
import pytest_asyncio
from fastapi.testclient import TestClient
from fastapi import status
from unittest.mock import AsyncMock, MagicMock, patch, Mock
from datetime import datetime, timedelta
import json
import os
import asyncio
from typing import AsyncGenerator, Generator
import httpx
from contextlib import asynccontextmanager

# Set test environment variables before importing app
os.environ["BRIDGE_API_KEY"] = "test-api-key-12345"
os.environ["DATABASE_URL"] = "postgresql://postgres:test@localhost:5432/test_db"

# Import app components (assuming bridge_api.py structure)
# Note: In real implementation, these would come from bridge_api.py
from pydantic import BaseModel, Field
from enum import Enum
from fastapi import FastAPI, Depends, HTTPException, Header, Query, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.middleware.trustedhost import TrustedHostMiddleware
from slowapi import Limiter, _rate_limit_exceeded_handler
from slowapi.util import get_remote_address
from slowapi.errors import RateLimitExceeded
import psycopg
from psycopg_pool import AsyncConnectionPool
import uuid
import time

# Pydantic Models (mirroring expected bridge_api.py models)
class CommandType(str, Enum):
    EXECUTE = "execute"
    QUERY = "query"
    UPDATE = "update"
    DELETE = "delete"
    NOTIFY = "notify"

class DirectiveStatus(str, Enum):
    PENDING = "pending"
    PROCESSING = "processing"
    COMPLETED = "completed"
    FAILED = "failed"
    EXPIRED = "expired"

class DirectiveCreate(BaseModel):
    command_type: CommandType
    payload: dict
    priority: int = Field(default=5, ge=1, le=10)
    source: str = Field(..., min_length=1, max_length=255)
    target: str = Field(default="claude", min_length=1, max_length=255)
    metadata: dict = Field(default_factory=dict)
    expires_in_seconds: int = Field(default=3600, ge=60, le=86400)

class DirectiveResponse(BaseModel):
    id: str
    status: DirectiveStatus
    created_at: datetime
    updated_at: datetime | None = None
    command_type: CommandType
    priority: int
    source: str
    target: str
    payload: dict
    metadata: dict
    expires_at: datetime
    response_payload: dict | None = None
    error_message: str | None = None

class StatusUpdate(BaseModel):
    directive_id: str
    status: DirectiveStatus
    response_payload: dict | None = None
    error_message: str | None = None

class SystemStatus(BaseModel):
    pending_count: int
    processing_count: int
    completed_today: int
    failed_today: int
    last_directive_at: datetime | None = None
    uptime_seconds: float

class HealthCheck(BaseModel):
    status: str
    db_connected: bool
    uptime_seconds: float

class HistoryQuery(BaseModel):
    limit: int = Query(default=50, ge=1, le=1000)
    offset: int = Query(default=0, ge=0)
    direction: str = Query(default="desc", regex="^(asc|desc)$")
    date_from: datetime | None = None
    date_to: datetime | None = None

# Database setup
class Database:
    def __init__(self):
        self.pool: AsyncConnectionPool | None = None
        self.start_time = time.time()
    
    async def connect(self):
        dsn = os.getenv("DATABASE_URL")
        self.pool = AsyncConnectionPool(dsn, min_size=1, max_size=10)
    
    async def disconnect(self):
        if self.pool:
            await self.pool.close()
    
    async def execute(self, query: str, *args):
        if not self.pool:
            raise Exception("Database not connected")
        async with self.pool.connection() as conn:
            return await conn.execute(query, *args)
    
    async def fetchone(self, query: str, *args):
        if not self.pool:
            raise Exception("Database not connected")
        async with self.pool.connection() as conn:
            async with conn.cursor() as cur:
                await cur.execute(query, *args)
                return await cur.fetchone()
    
    async def fetchall(self, query: str, *args):
        if not self.pool:
            raise Exception("Database not connected")
        async with self.pool.connection() as conn:
            async with conn.cursor() as cur:
                await cur.execute(query, *args)
                return await cur.fetchall()

db = Database()

# FastAPI App
limiter = Limiter(key_func=get_remote_address)
app = FastAPI(title="AIVA Command Bridge API", version="2.0.0")
app.state.limiter = limiter
app.add_exception_handler(RateLimitExceeded, _rate_limit_exceeded_handler)

app.add_middleware(
    CORSMiddleware,
    allow_origins=["*"],
    allow_credentials=True,
    allow_methods=["*"],
    allow_headers=["*"],
)

API_KEY = os.getenv("BRIDGE_API_KEY", "dev-key")

async def verify_api_key(x_api_key: str = Header(...)):
    if x_api_key != API_KEY:
        raise HTTPException(status_code=403, detail="Invalid API Key")
    return x_api_key

@app.on_event("startup")
async def startup():
    await db.connect()
    await db.execute("""
        CREATE SCHEMA IF NOT EXISTS genesis_bridge;
        CREATE TABLE IF NOT EXISTS genesis_bridge.directives (
            id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
            command_type VARCHAR(50) NOT NULL,
            payload JSONB NOT NULL DEFAULT '{}',
            priority INTEGER NOT NULL DEFAULT 5 CHECK (priority >= 1 AND priority <= 10),
            source VARCHAR(255) NOT NULL,
            target VARCHAR(255) NOT NULL DEFAULT 'claude',
            metadata JSONB NOT NULL DEFAULT '{}',
            status VARCHAR(50) NOT NULL DEFAULT 'pending',
            created_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
            updated_at TIMESTAMP WITH TIME ZONE DEFAULT NOW(),
            expires_at TIMESTAMP WITH TIME ZONE DEFAULT NOW() + INTERVAL '1 hour',
            response_payload JSONB,
            error_message TEXT
        );
        CREATE INDEX IF NOT EXISTS idx_directives_status ON genesis_bridge.directives(status);
        CREATE INDEX IF NOT EXISTS idx_directives_target ON genesis_bridge.directives(target);
        CREATE INDEX IF NOT EXISTS idx_directives_priority ON genesis_bridge.directives(priority DESC, created_at ASC);
    """)

@app.on_event("shutdown")
async def shutdown():
    await db.disconnect()

@app.post("/bridge/directive", response_model=DirectiveResponse, status_code=201)
@limiter.limit("100/minute")
async def create_directive(
    request: Request,
    directive: DirectiveCreate,
    api_key: str = Depends(verify_api_key)
):
    try:
        expires_at = datetime.utcnow() + timedelta(seconds=directive.expires_in_seconds)
        
        row = await db.fetchone(
            """
            INSERT INTO genesis_bridge.directives 
            (command_type, payload, priority, source, target, metadata, status, expires_at)
            VALUES ($1, $2, $3, $4, $5, $6, 'pending', $7)
            RETURNING id, command_type, payload, priority, source, target, metadata, 
                      status, created_at, updated_at, expires_at, response_payload, error_message
            """,
            directive.command_type.value,
            json.dumps(directive.payload),
            directive.priority,
            directive.source,
            directive.target,
            json.dumps(directive.metadata),
            expires_at
        )
        
        return DirectiveResponse(
            id=str(row[0]),
            command_type=row[1],
            payload=row[2],
            priority=row[3],
            source=row[4],
            target=row[5],
            metadata=row[6],
            status=row[7],
            created_at=row[8],
            updated_at=row[9],
            expires_at=row[10],
            response_payload=row[11],
            error_message=row[12]
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")

@app.get("/bridge/directives", response_model=list[DirectiveResponse])
@limiter.limit("100/minute")
async def get_directives(
    request: Request,
    target: str = Query(default="claude"),
    status: str = Query(default="pending"),
    limit: int = Query(default=10, ge=1, le=100),
    min_priority: int = Query(default=1, ge=1, le=10),
    api_key: str = Depends(verify_api_key)
):
    try:
        # Fetch directives
        rows = await db.fetchall(
            """
            SELECT id, command_type, payload, priority, source, target, metadata, 
                   status, created_at, updated_at, expires_at, response_payload, error_message
            FROM genesis_bridge.directives
            WHERE target = $1 AND status = $2 AND priority >= $3
            ORDER BY priority DESC, created_at ASC
            LIMIT $4
            FOR UPDATE SKIP LOCKED
            """,
            target, status, min_priority, limit
        )
        
        if not rows:
            return []
        
        # Update status to processing
        ids = [row[0] for row in rows]
        await db.execute(
            """
            UPDATE genesis_bridge.directives 
            SET status = 'processing', updated_at = NOW()
            WHERE id = ANY($1)
            """,
            ids
        )
        
        return [
            DirectiveResponse(
                id=str(row[0]),
                command_type=row[1],
                payload=row[2],
                priority=row[3],
                source=row[4],
                target=row[5],
                metadata=row[6],
                status='processing',  # Updated status
                created_at=row[8],
                updated_at=datetime.utcnow(),
                expires_at=row[10],
                response_payload=row[11],
                error_message=row[12]
            )
            for row in rows
        ]
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")

@app.post("/bridge/status", response_model=DirectiveResponse)
@limiter.limit("100/minute")
async def update_status(
    request: Request,
    update: StatusUpdate,
    api_key: str = Depends(verify_api_key)
):
    try:
        row = await db.fetchone(
            """
            UPDATE genesis_bridge.directives 
            SET status = $1, 
                response_payload = $2,
                error_message = $3,
                updated_at = NOW()
            WHERE id = $4
            RETURNING id, command_type, payload, priority, source, target, metadata, 
                      status, created_at, updated_at, expires_at, response_payload, error_message
            """,
            update.status.value,
            json.dumps(update.response_payload) if update.response_payload else None,
            update.error_message,
            update.directive_id
        )
        
        if not row:
            raise HTTPException(status_code=404, detail="Directive not found")
        
        return DirectiveResponse(
            id=str(row[0]),
            command_type=row[1],
            payload=row[2],
            priority=row[3],
            source=row[4],
            target=row[5],
            metadata=row[6],
            status=row[7],
            created_at=row[8],
            updated_at=row[9],
            expires_at=row[10],
            response_payload=row[11],
            error_message=row[12]
        )
    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")

@app.get("/bridge/status", response_model=SystemStatus)
@limiter.limit("100/minute")
async def get_system_status(
    request: Request,
    api_key: str = Depends(verify_api_key)
):
    try:
        today = datetime.utcnow().date()
        
        # Get counts
        pending = await db.fetchone("SELECT COUNT(*) FROM genesis_bridge.directives WHERE status = 'pending'")
        processing = await db.fetchone("SELECT COUNT(*) FROM genesis_bridge.directives WHERE status = 'processing'")
        completed = await db.fetchone("SELECT COUNT(*) FROM genesis_bridge.directives WHERE status = 'completed' AND DATE(updated_at) = $1", today)
        failed = await db.fetchone("SELECT COUNT(*) FROM genesis_bridge.directives WHERE status = 'failed' AND DATE(updated_at) = $1", today)
        last = await db.fetchone("SELECT MAX(created_at) FROM genesis_bridge.directives")
        
        uptime = time.time() - db.start_time
        
        return SystemStatus(
            pending_count=pending[0] if pending else 0,
            processing_count=processing[0] if processing else 0,
            completed_today=completed[0] if completed else 0,
            failed_today=failed[0] if failed else 0,
            last_directive_at=last[0] if last and last[0] else None,
            uptime_seconds=uptime
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")

@app.get("/bridge/health", response_model=HealthCheck)
async def health_check():
    db_connected = False
    try:
        if db.pool:
            # Quick connection check
            async with db.pool.connection() as conn:
                await conn.execute("SELECT 1")
                db_connected = True
    except:
        db_connected = False
    
    uptime = time.time() - db.start_time
    
    return HealthCheck(
        status="healthy" if db_connected else "unhealthy",
        db_connected=db_connected,
        uptime_seconds=uptime
    )

@app.get("/bridge/history", response_model=list[DirectiveResponse])
@limiter.limit("100/minute")
async def get_history(
    request: Request,
    limit: int = Query(default=50, ge=1, le=1000),
    offset: int = Query(default=0, ge=0),
    direction: str = Query(default="desc", regex="^(asc|desc)$"),
    date_from: datetime | None = None,
    date_to: datetime | None = None,
    api_key: str = Depends(verify_api_key)
):
    try:
        order = "DESC" if direction == "desc" else "ASC"
        
        query = f"""
            SELECT id, command_type, payload, priority, source, target, metadata, 
                   status, created_at, updated_at, expires_at, response_payload, error_message
            FROM genesis_bridge.directives
            WHERE 1=1
        """
        params = []
        param_idx = 1
        
        if date_from:
            query += f" AND created_at >= ${param_idx}"
            params.append(date_from)
            param_idx += 1
        
        if date_to:
            query += f" AND created_at <= ${param_idx}"
            params.append(date_to)
            param_idx += 1
        
        query += f" ORDER BY created_at {order}"
        query += f" LIMIT ${param_idx} OFFSET ${param_idx + 1}"
        params.extend([limit, offset])
        
        rows = await db.fetchall(query, *params)
        
        return [
            DirectiveResponse(
                id=str(row[0]),
                command_type=row[1],
                payload=row[2],
                priority=row[3],
                source=row[4],
                target=row[5],
                metadata=row[6],
                status=row[7],
                created_at=row[8],
                updated_at=row[9],
                expires_at=row[10],
                response_payload=row[11],
                error_message=row[12]
            )
            for row in rows
        ]
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"Database error: {str(e)}")

# Test Code Starts Here

import pytest
from httpx import AsyncClient, ASGITransport

# Fixtures

@pytest.fixture(scope="session")
def event_loop():
    """Create an instance of the default event loop for the test session."""
    loop = asyncio.get_event_loop_policy().new_event_loop()
    yield loop
    loop.close()

@pytest.fixture
async def mock_db_pool():
    """Create a mock database pool for testing."""
    pool = AsyncMock()
    pool.connection = MagicMock()
    pool.connection.return_value.__aenter__ = AsyncMock()
    pool.connection.return_value.__aexit__ = AsyncMock()
    return pool

@pytest.fixture
async def client(mock_db_pool, monkeypatch):
    """Create a test client with mocked database."""
    # Mock the database
    monkeypatch.setattr(db, "pool", mock_db_pool)
    db.start_time = time.time()
    
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
        yield ac

@pytest.fixture
def api_key():
    return "test-api-key-12345"

@pytest.fixture
def invalid_api_key():
    return "invalid-key"

@pytest.fixture
def sample_directive_payload():
    return {
        "command_type": "execute",
        "payload": {"action": "test_action", "data": "test_data"},
        "priority": 8,
        "source": "kinan",
        "target": "claude",
        "metadata": {"session_id": "test-123"},
        "expires_in_seconds": 3600
    }

@pytest.fixture
def mock_directive_row():
    return (
        "550e8400-e29b-41d4-a716-446655440000",  # id
        "execute",  # command_type
        {"action": "test"},  # payload
        8,  # priority
        "kinan",  # source
        "claude",  # target
        {"session": "test"},  # metadata
        "pending",  # status
        datetime.utcnow(),  # created_at
        datetime.utcnow(),  # updated_at
        datetime.utcnow() + timedelta(hours=1),  # expires_at
        None,  # response_payload
        None   # error_message
    )

# Test Classes

class TestHealthEndpoints:
    """Tests for health check endpoints."""
    
    @pytest.mark.asyncio
    async def test_health_check_healthy(self, client, mock_db_pool):
        """Test health check when database is connected."""
        # Mock successful DB check
        mock_conn = AsyncMock()
        mock_conn.execute = AsyncMock()
        mock_db_pool.connection.return_value.__aenter__ = AsyncMock(return_value=mock_conn)
        mock_db_pool.connection.return_value.__aexit__ = AsyncMock(return_value=False)
        
        response = await client.get("/bridge/health")
        assert response.status_code == 200
        data = response.json()
        assert data["status"] == "healthy"
        assert data["db_connected"] is True
        assert "uptime_seconds" in data
    
    @pytest.mark.asyncio
    async def test_health_check_unhealthy(self, client):
        """Test health check when database is disconnected."""
        # Mock no pool
        db.pool = None
        
        response = await client.get("/bridge/health")
        assert response.status_code == 200
        data = response.json()
        assert data["status"] == "unhealthy"
        assert data["db_connected"] is False

class TestAuthentication:
    """Tests for API key authentication."""
    
    @pytest.mark.asyncio
    async def test_missing_api_key(self, client):
        """Test request without API key."""
        response = await client.post("/bridge/directive", json={})
        assert response.status_code == 403
    
    @pytest.mark.asyncio
    async def test_invalid_api_key(self, client, invalid_api_key):
        """Test request with invalid API key."""
        response = await client.post(
            "/bridge/directive", 
            json={},
            headers={"X-API-Key": invalid_api_key}
        )
        assert response.status_code == 403
    
    @pytest.mark.asyncio
    async def test_valid_api_key(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test request with valid API key."""
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {},
                "source": "test",
                "target": "claude"
            },
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 201

class TestDirectiveCreation:
    """Tests for POST /bridge/directive endpoint."""
    
    @pytest.mark.asyncio
    async def test_create_directive_success(self, client, api_key, sample_directive_payload, mock_db_pool, mock_directive_row):
        """Test successful directive creation."""
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        
        response = await client.post(
            "/bridge/directive",
            json=sample_directive_payload,
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 201
        data = response.json()
        assert data["command_type"] == "execute"
        assert data["priority"] == 8
        assert data["status"] == "pending"
    
    @pytest.mark.asyncio
    async def test_create_directive_validation_error(self, client, api_key):
        """Test directive creation with invalid data."""
        invalid_payload = {
            "command_type": "invalid_type",  # Invalid enum value
            "payload": {},
            "source": "test"
        }
        
        response = await client.post(
            "/bridge/directive",
            json=invalid_payload,
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422
    
    @pytest.mark.asyncio
    async def test_create_directive_priority_bounds(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test priority validation (1-10)."""
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        
        # Test priority > 10
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {},
                "source": "test",
                "priority": 11
            },
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422
        
        # Test priority < 1
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {},
                "source": "test",
                "priority": 0
            },
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422
    
    @pytest.mark.asyncio
    async def test_create_directive_database_error(self, client, api_key, sample_directive_payload, mock_db_pool):
        """Test handling of database errors."""
        mock_db_pool.fetchone = AsyncMock(side_effect=Exception("Connection refused"))
        
        response = await client.post(
            "/bridge/directive",
            json=sample_directive_payload,
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 500

class TestDirectiveRetrieval:
    """Tests for GET /bridge/directives endpoint."""
    
    @pytest.mark.asyncio
    async def test_get_directives_success(self, client, api_key, mock_db_pool):
        """Test retrieving pending directives."""
        mock_rows = [
            (
                "550e8400-e29b-41d4-a716-446655440000",
                "execute", {"action": "test"}, 8, "kinan", "claude",
                {}, "pending", datetime.utcnow(), datetime.utcnow(),
                datetime.utcnow() + timedelta(hours=1), None, None
            )
        ]
        mock_db_pool.fetchall = AsyncMock(return_value=mock_rows)
        mock_db_pool.execute = AsyncMock(return_value=None)
        
        response = await client.get(
            "/bridge/directives?target=claude&status=pending",
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 200
        data = response.json()
        assert len(data) == 1
        assert data[0]["status"] == "processing"  # Should be updated to processing
        assert data[0]["target"] == "claude"
    
    @pytest.mark.asyncio
    async def test_get_directives_with_priority_filter(self, client, api_key, mock_db_pool):
        """Test filtering by minimum priority."""
        mock_db_pool.fetchall = AsyncMock(return_value=[])
        mock_db_pool.execute = AsyncMock(return_value=None)
        
        response = await client.get(
            "/bridge/directives?target=claude&min_priority=8",
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 200
        assert response.json() == []
    
    @pytest.mark.asyncio
    async def test_get_directives_limit_validation(self, client, api_key):
        """Test limit parameter validation."""
        response = await client.get(
            "/bridge/directives?limit=0",
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422
        
        response = await client.get(
            "/bridge/directives?limit=101",
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422

class TestStatusUpdate:
    """Tests for POST /bridge/status endpoint."""
    
    @pytest.mark.asyncio
    async def test_update_status_success(self, client, api_key, mock_db_pool):
        """Test successful status update."""
        mock_row = (
            "550e8400-e29b-41d4-a716-446655440000",
            "execute", {"action": "test"}, 8, "kinan", "claude",
            {}, "completed", datetime.utcnow(), datetime.utcnow(),
            datetime.utcnow() + timedelta(hours=1), {"result": "success"}, None
        )
        mock_db_pool.fetchone = AsyncMock(return_value=mock_row)
        
        response = await client.post(
            "/bridge/status",
            json={
                "directive_id": "550e8400-e29b-41d4-a716-446655440000",
                "status": "completed",
                "response_payload": {"result": "success"}
            },
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 200
        data = response.json()
        assert data["status"] == "completed"
        assert data["response_payload"] == {"result": "success"}
    
    @pytest.mark.asyncio
    async def test_update_status_not_found(self, client, api_key, mock_db_pool):
        """Test updating non-existent directive."""
        mock_db_pool.fetchone = AsyncMock(return_value=None)
        
        response = await client.post(
            "/bridge/status",
            json={
                "directive_id": "non-existent-uuid",
                "status": "completed"
            },
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 404
    
    @pytest.mark.asyncio
    async def test_update_status_with_error(self, client, api_key, mock_db_pool):
        """Test status update with error message."""
        mock_row = (
            "550e8400-e29b-41d4-a716-446655440000",
            "execute", {"action": "test"}, 8, "kinan", "claude",
            {}, "failed", datetime.utcnow(), datetime.utcnow(),
            datetime.utcnow() + timedelta(hours=1), None, "Connection timeout"
        )
        mock_db_pool.fetchone = AsyncMock(return_value=mock_row)
        
        response = await client.post(
            "/bridge/status",
            json={
                "directive_id": "550e8400-e29b-41d4-a716-446655440000",
                "status": "failed",
                "error_message": "Connection timeout"
            },
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 200
        data = response.json()
        assert data["status"] == "failed"
        assert data["error_message"] == "Connection timeout"

class TestSystemStatus:
    """Tests for GET /bridge/status (system status) endpoint."""
    
    @pytest.mark.asyncio
    async def test_get_system_status(self, client, api_key, mock_db_pool):
        """Test retrieving system status."""
        mock_db_pool.fetchone = AsyncMock(side_effect=[
            (5,),   # pending
            (2,),   # processing
            (10,),  # completed today
            (1,),   # failed today
            (datetime.utcnow(),)  # last directive
        ])
        
        response = await client.get(
            "/bridge/status",
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 200
        data = response.json()
        assert data["pending_count"] == 5
        assert data["processing_count"] == 2
        assert data["completed_today"] == 10
        assert data["failed_today"] == 1
        assert "last_directive_at" in data
        assert "uptime_seconds" in data

class TestHistory:
    """Tests for GET /bridge/history endpoint."""
    
    @pytest.mark.asyncio
    async def test_get_history(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test retrieving command history."""
        mock_db_pool.fetchall = AsyncMock(return_value=[mock_directive_row])
        
        response = await client.get(
            "/bridge/history?limit=10&offset=0",
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 200
        data = response.json()
        assert len(data) == 1
        assert data[0]["id"] == "550e8400-e29b-41d4-a716-446655440000"
    
    @pytest.mark.asyncio
    async def test_get_history_with_date_range(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test history with date filters."""
        mock_db_pool.fetchall = AsyncMock(return_value=[mock_directive_row])
        
        date_from = datetime.utcnow() - timedelta(days=7)
        date_to = datetime.utcnow()
        
        response = await client.get(
            f"/bridge/history?date_from={date_from.isoformat()}&date_to={date_to.isoformat()}",
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 200
    
    @pytest.mark.asyncio
    async def test_get_history_pagination(self, client, api_key, mock_db_pool):
        """Test history pagination."""
        mock_db_pool.fetchall = AsyncMock(return_value=[])
        
        response = await client.get(
            "/bridge/history?limit=50&offset=100",
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 200
        assert response.json() == []

class TestRateLimiting:
    """Tests for rate limiting."""
    
    @pytest.mark.asyncio
    async def test_rate_limiting(self, client, api_key, mock_db_pool):
        """Test that rate limiting is enforced."""
        # Mock successful response for health check (no rate limit on health)
        mock_db_pool.fetchone = AsyncMock(return_value=(1,))
        
        # Health endpoint doesn't have rate limit in our implementation
        # But directive creation does
        response = await client.get("/bridge/health")
        assert response.status_code == 200

class TestCORS:
    """Tests for CORS configuration."""
    
    @pytest.mark.asyncio
    async def test_cors_headers(self, client):
        """Test CORS headers are present."""
        response = await client.options("/bridge/health", headers={
            "Origin": "http://localhost:3000",
            "Access-Control-Request-Method": "GET"
        })
        assert response.status_code == 200
        assert "access-control-allow-origin" in response.headers

class TestEdgeCases:
    """Edge case and error handling tests."""
    
    @pytest.mark.asyncio
    async def test_create_directive_empty_payload(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test directive with empty payload."""
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        
        payload = {
            "command_type": "execute",
            "payload": {},
            "source": "test",
            "target": "claude"
        }
        
        response = await client.post(
            "/bridge/directive",
            json=payload,
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 201
    
    @pytest.mark.asyncio
    async def test_create_directive_large_payload(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test directive with large payload."""
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        
        large_payload = {
            "command_type": "execute",
            "payload": {"data": "x" * 10000},  # Large string
            "source": "test",
            "target": "claude"
        }
        
        response = await client.post(
            "/bridge/directive",
            json=large_payload,
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 201
    
    @pytest.mark.asyncio
    async def test_sql_injection_attempt(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test that SQL injection attempts are handled safely."""
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        
        malicious_payload = {
            "command_type": "execute",
            "payload": {"data": "'; DROP TABLE genesis_bridge.directives; --"},
            "source": "test'; DROP TABLE users; --",
            "target": "claude"
        }
        
        response = await client.post(
            "/bridge/directive",
            json=malicious_payload,
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 201
        # Verify the data was treated as strings, not executed
        call_args = mock_db_pool.fetchone.call_args
        assert "'; DROP TABLE" in str(call_args)
    
    @pytest.mark.asyncio
    async def test_concurrent_requests(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test handling of concurrent requests."""
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        
        async def make_request():
            return await client.post(
                "/bridge/directive",
                json={
                    "command_type": "execute",
                    "payload": {},
                    "source": "test",
                    "target": "claude"
                },
                headers={"X-API-Key": api_key}
            )
        
        # Make 5 concurrent requests
        responses = await asyncio.gather(*[make_request() for _ in range(5)])
        
        for response in responses:
            assert response.status_code == 201
    
    @pytest.mark.asyncio
    async def test_expired_directive_handling(self, client, api_key, mock_db_pool):
        """Test that expired directives are handled correctly."""
        expired_row = (
            "550e8400-e29b-41d4-a716-446655440000",
            "execute", {}, 5, "kinan", "claude",
            {}, "expired", datetime.utcnow() - timedelta(hours=2),
            datetime.utcnow() - timedelta(hours=1),
            datetime.utcnow() - timedelta(hours=1),  # expired
            None, None
        )
        mock_db_pool.fetchall = AsyncMock(return_value=[expired_row])
        mock_db_pool.execute = AsyncMock(return_value=None)
        
        response = await client.get(
            "/bridge/directives?status=expired",
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 200
        data = response.json()
        assert len(data) == 1

class TestIntegration:
    """Integration-style tests simulating full workflow."""
    
    @pytest.mark.asyncio
    async def test_full_workflow(self, client, api_key, mock_db_pool):
        """Test complete workflow: create -> get -> update -> check status."""
        # Setup mock responses for each step
        directive_id = "550e8400-e29b-41d4-a716-446655440000"
        created_row = (
            directive_id, "execute", {"action": "process"}, 8, "kinan", "claude",
            {}, "pending", datetime.utcnow(), datetime.utcnow(),
            datetime.utcnow() + timedelta(hours=1), None, None
        )
        processing_row = (
            directive_id, "execute", {"action": "process"}, 8, "kinan", "claude",
            {}, "processing", datetime.utcnow(), datetime.utcnow(),
            datetime.utcnow() + timedelta(hours=1), None, None
        )
        completed_row = (
            directive_id, "execute", {"action": "process"}, 8, "kinan", "claude",
            {}, "completed", datetime.utcnow(), datetime.utcnow(),
            datetime.utcnow() + timedelta(hours=1), {"result": "done"}, None
        )
        
        # Step 1: Create directive
        mock_db_pool.fetchone = AsyncMock(return_value=created_row)
        create_response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {"action": "process"},
                "priority": 8,
                "source": "kinan",
                "target": "claude"
            },
            headers={"X-API-Key": api_key}
        )
        assert create_response.status_code == 201
        created_data = create_response.json()
        assert created_data["status"] == "pending"
        
        # Step 2: Get directives (should mark as processing)
        mock_db_pool.fetchall = AsyncMock(return_value=[created_row])
        mock_db_pool.execute = AsyncMock(return_value=None)
        
        get_response = await client.get(
            "/bridge/directives?target=claude",
            headers={"X-API-Key": api_key}
        )
        assert get_response.status_code == 200
        directives = get_response.json()
        assert len(directives) == 1
        assert directives[0]["status"] == "processing"
        
        # Step 3: Update status to completed
        mock_db_pool.fetchone = AsyncMock(return_value=completed_row)
        
        update_response = await client.post(
            "/bridge/status",
            json={
                "directive_id": directive_id,
                "status": "completed",
                "response_payload": {"result": "done"}
            },
            headers={"X-API-Key": api_key}
        )
        assert update_response.status_code == 200
        updated = update_response.json()
        assert updated["status"] == "completed"
        assert updated["response_payload"] == {"result": "done"}

# Database Error Tests

class TestDatabaseErrors:
    """Tests for database error handling."""
    
    @pytest.mark.asyncio
    async def test_database_connection_failure_directive_creation(self, client, api_key, sample_directive_payload, mock_db_pool):
        """Test handling of DB connection failure during creation."""
        mock_db_pool.fetchone = AsyncMock(side_effect=psycopg.OperationalError("Connection refused"))
        
        response = await client.post(
            "/bridge/directive",
            json=sample_directive_payload,
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 500
        assert "Database error" in response.json()["detail"]
    
    @pytest.mark.asyncio
    async def test_database_timeout(self, client, api_key, mock_db_pool):
        """Test handling of database timeout."""
        mock_db_pool.fetchall = AsyncMock(side_effect=asyncio.TimeoutError("Query timeout"))
        
        response = await client.get(
            "/bridge/directives",
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 500

# Performance and Load Tests

class TestPerformance:
    """Performance-related tests."""
    
    @pytest.mark.asyncio
    async def test_large_payload_handling(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test handling of large JSON payloads."""
        large_payload = {
            "command_type": "execute",
            "payload": {
                "data": "x" * 100000,  # 100KB of data
                "nested": {
                    "array": list(range(1000)),
                    "text": "Test " * 1000
                }
            },
            "source": "kinan",
            "target": "claude",
            "metadata": {"large": True}
        }
        
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        
        response = await client.post(
            "/bridge/directive",
            json=large_payload,
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 201
    
    @pytest.mark.asyncio
    async def test_high_priority_directive(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test that high priority directives are processed correctly."""
        high_priority_row = list(mock_directive_row)
        high_priority_row[3] = 10  # priority
        
        mock_db_pool.fetchone = AsyncMock(return_value=tuple(high_priority_row))
        
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {"urgent": True},
                "priority": 10,
                "source": "kinan",
                "target": "claude"
            },
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 201
        assert response.json()["priority"] == 10

# Security Tests

class TestSecurity:
    """Security-focused tests."""
    
    @pytest.mark.asyncio
    async def test_sql_injection_in_source(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test SQL injection attempt in source field."""
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        
        malicious_source = "kinan'; DROP TABLE genesis_bridge.directives; --"
        
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {},
                "source": malicious_source,
                "target": "claude"
            },
            headers={"X-API-Key": api_key}
        )
        
        # Should succeed (parameterized query prevents injection)
        assert response.status_code == 201
        
        # Verify the malicious string was stored as-is (not executed)
        call_args = mock_db_pool.fetchone.call_args
        assert malicious_source in str(call_args)
    
    @pytest.mark.asyncio
    async def test_no_sql_injection_in_payload(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test that JSON payload doesn't allow SQL injection."""
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        
        malicious_payload = {
            "command_type": "execute",
            "payload": {
                "query": "'; DELETE FROM genesis_bridge.directives WHERE '1'='1"
            },
            "source": "test",
            "target": "claude"
        }
        
        response = await client.post(
            "/bridge/directive",
            json=malicious_payload,
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 201
    
    @pytest.mark.asyncio
    async def test_cors_preflight(self, client):
        """Test CORS preflight request."""
        response = await client.options(
            "/bridge/directive",
            headers={
                "Origin": "http://localhost:3000",
                "Access-Control-Request-Method": "POST",
                "Access-Control-Request-Headers": "X-API-Key"
            }
        )
        
        assert response.status_code == 200
        assert "access-control-allow-origin" in response.headers
        assert "access-control-allow-methods" in response.headers

# Schema Validation Tests

class TestSchemaValidation:
    """Tests for Pydantic schema validation."""
    
    @pytest.mark.asyncio
    async def test_invalid_command_type(self, client, api_key):
        """Test validation of command_type enum."""
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "invalid_command",
                "payload": {},
                "source": "test"
            },
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422
    
    @pytest.mark.asyncio
    async def test_invalid_status_update(self, client, api_key):
        """Test validation of status enum in update."""
        response = await client.post(
            "/bridge/status",
            json={
                "directive_id": "test-id",
                "status": "invalid_status"
            },
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422
    
    @pytest.mark.asyncio
    async def test_missing_required_fields(self, client, api_key):
        """Test validation of required fields."""
        response = await client.post(
            "/bridge/directive",
            json={
                "payload": {}
                # Missing command_type and source
            },
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422
    
    @pytest.mark.asyncio
    async def test_field_length_limits(self, client, api_key):
        """Test validation of field length limits."""
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {},
                "source": "x" * 300,  # Exceeds 255 limit
                "target": "claude"
            },
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422

# Database Connection Pool Tests

class TestDatabasePool:
    """Tests for database connection pool management."""
    
    @pytest.mark.asyncio
    async def test_pool_exhaustion_handling(self, client, api_key, mock_db_pool):
        """Test handling when connection pool is exhausted."""
        mock_db_pool.fetchone = AsyncMock(side_effect=psycopg.PoolTimeout("Connection pool exhausted"))
        
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {},
                "source": "test",
                "target": "claude"
            },
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 500
    
    @pytest.mark.asyncio
    async def test_database_reconnection(self, client, mock_db_pool):
        """Test health check reflects database reconnection status."""
        # First call - DB down
        mock_db_pool.connection.side_effect = Exception("Connection refused")
        db.pool = mock_db_pool
        
        response = await client.get("/bridge/health")
        assert response.status_code == 200
        assert response.json()["db_connected"] is False
        
        # Second call - DB up
        mock_conn = AsyncMock()
        mock_db_pool.connection = MagicMock()
        mock_db_pool.connection.return_value.__aenter__ = AsyncMock(return_value=mock_conn)
        mock_db_pool.connection.return_value.__aexit__ = AsyncMock(return_value=False)
        
        response = await client.get("/bridge/health")
        assert response.status_code == 200
        assert response.json()["db_connected"] is True

# Startup/Shutdown Event Tests

class TestLifecycle:
    """Tests for application startup and shutdown events."""
    
    @pytest.mark.asyncio
    async def test_startup_event(self, mock_db_pool):
        """Test that startup event initializes database."""
        with patch('psycopg_pool.AsyncConnectionPool') as mock_pool_class:
            mock_pool_class.return_value = mock_db_pool
            await startup()
            mock_db_pool.open.assert_called_once()
    
    @pytest.mark.asyncio
    async def test_shutdown_event(self, mock_db_pool):
        """Test that shutdown event closes database connections."""
        db.pool = mock_db_pool
        await shutdown()
        mock_db_pool.close.assert_called_once()

# Parameterized Tests for Comprehensive Coverage

@pytest.mark.parametrize("command_type", ["execute", "query", "update", "delete", "notify"])
@pytest.mark.asyncio
async def test_all_command_types(client, api_key, mock_db_pool, command_type):
    """Test that all command types are accepted."""
    mock_row = (
        "550e8400-e29b-41d4-a716-446655440000",
        command_type, {}, 5, "kinan", "claude",
        {}, "pending", datetime.utcnow(), datetime.utcnow(),
        datetime.utcnow() + timedelta(hours=1), None, None
    )
    mock_db_pool.fetchone = AsyncMock(return_value=mock_row)
    
    response = await client.post(
        "/bridge/directive",
        json={
            "command_type": command_type,
            "payload": {"test": "data"},
            "source": "kinan",
            "target": "claude"
        },
        headers={"X-API-Key": api_key}
    )
    assert response.status_code == 201
    assert response.json()["command_type"] == command_type

@pytest.mark.parametrize("status", ["pending", "processing", "completed", "failed", "expired"])
@pytest.mark.asyncio
async def test_all_status_transitions(client, api_key, mock_db_pool, status):
    """Test that all status values work in updates."""
    mock_row = (
        "550e8400-e29b-41d4-a716-446655440000",
        "execute", {}, 5, "kinan", "claude",
        {}, status, datetime.utcnow(), datetime.utcnow(),
        datetime.utcnow() + timedelta(hours=1), 
        {"result": "ok"} if status in ["completed"] else None,
        "Error" if status in ["failed"] else None
    )
    mock_db_pool.fetchone = AsyncMock(return_value=mock_row)
    
    response = await client.post(
        "/bridge/status",
        json={
            "directive_id": "550e8400-e29b-41d4-a716-446655440000",
            "status": status,
            "response_payload": {"result": "ok"} if status == "completed" else None,
            "error_message": "Error" if status == "failed" else None
        },
        headers={"X-API-Key": api_key}
    )
    
    if status in ["completed", "failed", "processing"]:
        assert response.status_code == 200
        assert response.json()["status"] == status
    else:
        # Some statuses might not be valid for update (like pending, expired)
        # depending on business logic, but assuming they are valid for this test
        assert response.status_code in [200, 400, 422]

# Fixture for pytest-asyncio
@pytest_asyncio.fixture
async def async_client():
    """Provide an async HTTP client."""
    async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as ac:
        yield ac

# Additional integration tests using the async_client fixture

@pytest.mark.asyncio
async def test_end_to_end_workflow(async_client, mock_db_pool, api_key):
    """Test complete end-to-end workflow with mocked database."""
    # Mock data
    directive_id = "550e8400-e29b-41d4-a716-446655440000"
    created_time = datetime.utcnow()
    expires_time = created_time + timedelta(hours=1)
    
    created_row = (
        directive_id, "execute", {"action": "deploy"}, 9, "kinan", "claude",
        {"env": "prod"}, "pending", created_time, created_time,
        expires_time, None, None
    )
    
    processing_row = (
        directive_id, "execute", {"action": "deploy"}, 9, "kinan", "claude",
        {"env": "prod"}, "processing", created_time, datetime.utcnow(),
        expires_time, None, None
    )
    
    completed_row = (
        directive_id, "execute", {"action": "deploy"}, 9, "kinan", "claude",
        {"env": "prod"}, "completed", created_time, datetime.utcnow(),
        expires_time, {"status": "deployed", "version": "1.0.0"}, None
    )
    
    # 1. Create
    mock_db_pool.fetchone = AsyncMock(return_value=created_row)
    create_resp = await async_client.post(
        "/bridge/directive",
        json={
            "command_type": "execute",
            "payload": {"action": "deploy"},
            "priority": 9,
            "source": "kinan",
            "target": "claude",
            "metadata": {"env": "prod"}
        },
        headers={"X-API-Key": api_key}
    )
    assert create_resp.status_code == 201
    created = create_resp.json()
    assert created["priority"] == 9
    
    # 2. Get (mark as processing)
    mock_db_pool.fetchall = AsyncMock(return_value=[created_row])
    mock_db_pool.execute = AsyncMock(return_value=None)
    
    get_resp = await async_client.get(
        "/bridge/directives?target=claude&min_priority=9",
        headers={"X-API-Key": api_key}
    )
    assert get_resp.status_code == 200
    directives = get_resp.json()
    assert len(directives) == 1
    
    # 3. Update to completed
    mock_db_pool.fetchone = AsyncMock(return_value=completed_row)
    
    update_resp = await async_client.post(
        "/bridge/status",
        json={
            "directive_id": directive_id,
            "status": "completed",
            "response_payload": {"status": "deployed", "version": "1.0.0"}
        },
        headers={"X-API-Key": api_key}
    )
    assert update_resp.status_code == 200
    updated = update_resp.json()
    assert updated["status"] == "completed"
    assert updated["response_payload"]["version"] == "1.0.0"

# Database Schema Validation Tests

class TestDatabaseSchema:
    """Tests validating database schema constraints."""
    
    @pytest.mark.asyncio
    async def test_priority_constraint_violation(self, client, api_key, mock_db_pool):
        """Test that priority outside 1-10 is rejected."""
        # This should be caught by Pydantic before DB, but testing both layers
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {},
                "source": "test",
                "priority": 15  # Invalid
            },
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422
    
    @pytest.mark.asyncio
    async def test_uuid_format_validation(self, client, api_key, mock_db_pool):
        """Test that invalid UUID format is handled."""
        mock_db_pool.fetchone = AsyncMock(return_value=None)
        
        response = await client.post(
            "/bridge/status",
            json={
                "directive_id": "not-a-valid-uuid",
                "status": "completed"
            },
            headers={"X-API-Key": api_key}
        )
        # Should either 404 (not found) or 422 (validation error)
        assert response.status_code in [404, 422]
    
    @pytest.mark.asyncio
    async def test_datetime_format_validation(self, client, api_key, mock_db_pool):
        """Test datetime format validation in history endpoint."""
        mock_db_pool.fetchall = AsyncMock(return_value=[])
        
        # Invalid date format
        response = await client.get(
            "/bridge/history?date_from=invalid-date",
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 422
        
        # Valid ISO format
        valid_date = datetime.utcnow().isoformat()
        response = await client.get(
            f"/bridge/history?date_from={valid_date}",
            headers={"X-API-Key": api_key}
        )
        assert response.status_code == 200

# Error Recovery Tests

class TestErrorRecovery:
    """Tests for error recovery scenarios."""
    
    @pytest.mark.asyncio
    async def test_partial_failure_in_batch_update(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test handling when some updates fail in batch."""
        # First call succeeds (fetch), second fails (update)
        mock_db_pool.fetchall = AsyncMock(return_value=[mock_directive_row, mock_directive_row])
        mock_db_pool.execute = AsyncMock(side_effect=Exception("Update failed"))
        
        response = await client.get(
            "/bridge/directives",
            headers={"X-API-Key": api_key}
        )
        # Should handle gracefully or return error
        assert response.status_code in [200, 500]
    
    @pytest.mark.asyncio
    async def test_retry_after_connection_failure(self, client, api_key, mock_db_pool, sample_directive_payload):
        """Test behavior after temporary connection failure."""
        # First attempt fails, second succeeds
        mock_db_pool.fetchone = AsyncMock(side_effect=[
            psycopg.OperationalError("Connection lost"),
            ("550e8400-e29b-41d4-a716-446655440000", "execute", {}, 5, "test", "claude", 
             {}, "pending", datetime.utcnow(), datetime.utcnow(), 
             datetime.utcnow() + timedelta(hours=1), None, None)
        ])
        
        # First request should fail
        response1 = await client.post(
            "/bridge/directive",
            json=sample_directive_payload,
            headers={"X-API-Key": api_key}
        )
        assert response1.status_code == 500
        
        # Second request should succeed (if retried, but currently each request is independent)
        # This test documents expected behavior - in production, retry logic would be at client level

# Metadata and Logging Tests

class TestMetadataHandling:
    """Tests for metadata field handling."""
    
    @pytest.mark.asyncio
    async def test_complex_metadata_structure(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test storing complex nested metadata."""
        complex_metadata = {
            "session": {
                "id": "sess-123",
                "user": {
                    "id": "user-456",
                    "roles": ["admin", "operator"]
                }
            },
            "tags": ["urgent", "production"],
            "metrics": {
                "latency": 0.45,
                "retries": 0
            }
        }
        
        modified_row = list(mock_directive_row)
        modified_row[6] = complex_metadata
        mock_db_pool.fetchone = AsyncMock(return_value=tuple(modified_row))
        
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {},
                "source": "kinan",
                "metadata": complex_metadata
            },
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 201
        data = response.json()
        assert data["metadata"]["session"]["user"]["roles"] == ["admin", "operator"]
    
    @pytest.mark.asyncio
    async def test_unicode_handling(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test handling of unicode characters in fields."""
        unicode_source = "用户测试 🚀 ñoño"
        modified_row = list(mock_directive_row)
        modified_row[4] = unicode_source
        mock_db_pool.fetchone = AsyncMock(return_value=tuple(modified_row))
        
        response = await client.post(
            "/bridge/directive",
            json={
                "command_type": "execute",
                "payload": {"message": "Hello 世界"},
                "source": unicode_source,
                "target": "claude"
            },
            headers={"X-API-Key": api_key}
        )
        
        assert response.status_code == 201
        assert response.json()["source"] == unicode_source

# Concurrent Access Tests

class TestConcurrency:
    """Tests for concurrent access scenarios."""
    
    @pytest.mark.asyncio
    async def test_concurrent_reads_and_writes(self, client, api_key, mock_db_pool, mock_directive_row):
        """Test system behavior under concurrent load."""
        mock_db_pool.fetchone = AsyncMock(return_value=mock_directive_row)
        mock_db_pool.fetchall = AsyncMock(return_value=[mock_directive_row])
        mock_db_pool.execute = AsyncMock(return_value=None)
        
        async def create_directive(i):
            return await client.post(
                "/bridge/directive",
                json={
                    "command_type": "execute",
                    "payload": {"index": i},
                    "source": "concurrent_test",
                    "target": "claude"
                },
                headers={"X-API-Key": api_key}
            )
        
        async def get_directives():
            return await client.get(
                "/bridge/directives?target=claude",
                headers={"X-API-Key": api_key}
            )
        
        # Run mixed workload
        tasks = [create_directive(i) for i in range(3)] + [get_directives() for _ in range(3)]
        results = await asyncio.gather(*tasks)
        
        for response in results:
            assert response.status_code in [200, 201]

# Main entry point for running tests
if __name__ == "__main__":
    pytest.main([__file__, "-v", "--cov=.", "--cov-report=term-missing"])