"""Few-shot examples for TimeoutError fixes (common in flaky tests)."""

TIMEOUT_ERROR_EXAMPLES = [
    {
        "error": {
            "type": "asyncio.TimeoutError",
            "message": "",
            "code": '''async def test_fetch_data():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://api.example.com/data") as resp:
            data = await asyncio.wait_for(resp.json(), timeout=1.0)
    assert data["status"] == "ok"''',
            "context": "External API call times out intermittently under CI load",
        },
        "analysis": {
            "root_cause": "The test makes a real HTTP call to an external API with a 1-second timeout. Under CI load or when the external API is slow, this timeout is too tight and causes intermittent failures.",
            "reasoning": "The TimeoutError occurs in wait_for() with a 1.0s timeout on a real HTTP call. External APIs have variable latency, especially in CI environments. The test should mock the external dependency.",
        },
        "fix": {
            "strategy": "mock_external_dependency",
            "diff": '''--- a/test_fetch.py
+++ b/test_fetch.py
@@ -1,5 +1,8 @@
+@responses.activate
 async def test_fetch_data():
-    async with aiohttp.ClientSession() as session:
-        async with session.get("https://api.example.com/data") as resp:
-            data = await asyncio.wait_for(resp.json(), timeout=1.0)
+    responses.add(
+        responses.GET,
+        "https://api.example.com/data",
+        json={"status": "ok"},
+    )
+    data = await fetch_data()
     assert data["status"] == "ok"''',
            "explanation": "Mock the external API call so the test doesn't depend on network conditions. This eliminates the timeout flakiness entirely.",
        },
    },
    {
        "error": {
            "type": "TimeoutError",
            "message": "Timeout waiting for lock",
            "code": '''def test_concurrent_write():
    lock = threading.Lock()
    results = []

    def writer(val):
        lock.acquire(timeout=0.5)
        results.append(val)
        lock.release()

    threads = [threading.Thread(target=writer, args=(i,)) for i in range(10)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()
    assert len(results) == 10''',
            "context": "Lock contention causes timeout under load",
        },
        "analysis": {
            "root_cause": "The lock.acquire(timeout=0.5) has a very short timeout. With 10 threads contending for the same lock, the cumulative wait time can exceed 0.5s for threads acquired later in the queue.",
            "reasoning": "With 10 threads and a 0.5s per-thread timeout, if each thread holds the lock for even a few ms, later threads in the queue will timeout. The timeout should be longer or the locking strategy should change.",
        },
        "fix": {
            "strategy": "increase_timeout_with_context_manager",
            "diff": '''--- a/test_concurrent.py
+++ b/test_concurrent.py
@@ -4,8 +4,7 @@

     def writer(val):
-        lock.acquire(timeout=0.5)
-        results.append(val)
-        lock.release()
+        with lock:
+            results.append(val)''',
            "explanation": "Use a context manager for the lock (no timeout) since the critical section is trivial. The original timeout was too short for 10 contending threads.",
        },
    },
    {
        "error": {
            "type": "asyncio.TimeoutError",
            "message": "",
            "code": '''async def test_cache_warmup():
    cache = Cache()
    await cache.warmup()
    result = await asyncio.wait_for(cache.get("key"), timeout=0.1)
    assert result is not None''',
            "context": "Cache warmup takes variable time",
        },
        "analysis": {
            "root_cause": "The cache.get() call has a 0.1s timeout, but cache warmup time varies. If warmup is still completing when get() is called, the result may not be available within 100ms.",
            "reasoning": "The 0.1s timeout on cache.get() is too tight. Although warmup() is awaited, the cache may still be populating entries asynchronously. The get() should wait for the specific key to be available.",
        },
        "fix": {
            "strategy": "await_specific_condition",
            "diff": '''--- a/test_cache.py
+++ b/test_cache.py
@@ -2,4 +2,4 @@
     cache = Cache()
     await cache.warmup()
-    result = await asyncio.wait_for(cache.get("key"), timeout=0.1)
+    result = await cache.get("key", timeout=5.0)
     assert result is not None''',
            "explanation": "Use the cache's built-in timeout parameter with a more generous timeout. The 0.1s timeout was insufficient for variable warmup times.",
        },
    },
]

TIMEOUT_ERROR_NEGATIVE_EXAMPLES = [
    {
        "bad_fix": '''async def test_fetch_data():
    try:
        async with aiohttp.ClientSession() as session:
            async with session.get("https://api.example.com/data") as resp:
                data = await asyncio.wait_for(resp.json(), timeout=30.0)
        assert data["status"] == "ok"
    except asyncio.TimeoutError:
        pytest.skip("External API too slow")''',
        "why_bad": "Increasing the timeout and adding a skip on failure just masks the problem. The test still depends on an external API. It should be mocked instead.",
    },
    {
        "bad_fix": '''async def test_cache_warmup():
    cache = Cache()
    await cache.warmup()
    await asyncio.sleep(2.0)  # Wait for cache to populate
    result = await cache.get("key")
    assert result is not None''',
        "why_bad": "Adding a hardcoded sleep(2.0) is fragile — it may be too short under load or wastefully long normally. Use an explicit wait condition instead of a fixed delay.",
    },
]
