"""Few-shot examples for KeyError fixes."""

KEY_ERROR_EXAMPLES = [
    {
        "error": {
            "type": "KeyError",
            "message": "'user_id'",
            "code": '''def get_user_name(response):
    return response["data"]["user_id"]''',
            "context": "API response missing expected key",
        },
        "analysis": {
            "root_cause": "The API response does not always contain 'user_id' in the 'data' object.",
            "reasoning": "The code assumes response['data']['user_id'] always exists. The KeyError on 'user_id' tells us the 'data' dict exists but sometimes lacks 'user_id'. This happens when the user lookup fails or returns partial data.",
        },
        "fix": {
            "strategy": "use_get_default",
            "diff": '''--- a/api.py
+++ b/api.py
@@ -1,2 +1,5 @@
 def get_user_name(response):
-    return response["data"]["user_id"]
+    data = response.get("data", {})
+    user_id = data.get("user_id")
+    if user_id is None:
+        raise ValueError("User ID not found in response")
+    return user_id''',
            "explanation": "Use .get() to safely access nested keys, then explicitly handle the missing case with a descriptive error rather than silently returning None.",
        },
    },
    {
        "error": {
            "type": "KeyError",
            "message": "'settings'",
            "code": '''def get_theme(user_data):
    return user_data["settings"]["theme"]''',
            "context": "User data dictionary may not have settings",
        },
        "analysis": {
            "root_cause": "New users don't have a 'settings' key in their user_data until they customize settings.",
            "reasoning": "The KeyError is on 'settings', meaning user_data exists but lacks 'settings'. This is a valid state for new users who haven't configured settings yet.",
        },
        "fix": {
            "strategy": "use_get_default",
            "diff": '''--- a/user.py
+++ b/user.py
@@ -1,2 +1,3 @@
 def get_theme(user_data):
-    return user_data["settings"]["theme"]
+    settings = user_data.get("settings", {})
+    return settings.get("theme", "default")''',
            "explanation": "Provide sensible defaults for both 'settings' and 'theme' since this is a valid state for new users.",
        },
    },
    {
        "error": {
            "type": "KeyError",
            "message": "'Authorization'",
            "code": '''def get_token(headers):
    return headers["Authorization"].split(" ")[1]''',
            "context": "HTTP request missing Authorization header",
        },
        "analysis": {
            "root_cause": "The Authorization header is not present in all requests - some endpoints allow unauthenticated access.",
            "reasoning": "The KeyError indicates headers dict exists but 'Authorization' key is missing. This is expected for public endpoints.",
        },
        "fix": {
            "strategy": "add_none_check",
            "diff": '''--- a/auth.py
+++ b/auth.py
@@ -1,2 +1,5 @@
 def get_token(headers):
-    return headers["Authorization"].split(" ")[1]
+    auth_header = headers.get("Authorization")
+    if not auth_header:
+        return None
+    return auth_header.split(" ")[1]''',
            "explanation": "Return None for unauthenticated requests, letting the caller decide whether to reject or allow the request.",
        },
    },
    {
        "error": {
            "type": "KeyError",
            "message": "'email'",
            "code": '''def process_users(users):
    emails = [user["email"] for user in users]
    return emails''',
            "context": "List comprehension fails on user without email",
        },
        "analysis": {
            "root_cause": "Some user objects in the list don't have an 'email' field - possibly deleted or incomplete users.",
            "reasoning": "The list comprehension fails when any user lacks 'email'. The error occurs inside the comprehension, meaning at least one user dict is missing the key.",
        },
        "fix": {
            "strategy": "add_validation",
            "diff": '''--- a/process.py
+++ b/process.py
@@ -1,3 +1,3 @@
 def process_users(users):
-    emails = [user["email"] for user in users]
+    emails = [user["email"] for user in users if "email" in user]
     return emails''',
            "explanation": "Filter out users without email in the comprehension. This handles incomplete user objects gracefully.",
        },
    },
    {
        "error": {
            "type": "KeyError",
            "message": "'config'",
            "code": '''import os
import json

def load_config():
    return json.loads(os.environ["config"])''',
            "context": "Environment variable not set",
        },
        "analysis": {
            "root_cause": "The 'config' environment variable is not set in the current environment.",
            "reasoning": "os.environ behaves like a dict and raises KeyError for missing keys. This is a configuration error, not a code bug.",
        },
        "fix": {
            "strategy": "handle_error",
            "diff": '''--- a/config.py
+++ b/config.py
@@ -2,2 +2,6 @@ import json

 def load_config():
-    return json.loads(os.environ["config"])
+    config_str = os.environ.get("config")
+    if not config_str:
+        raise EnvironmentError(
+            "Required environment variable 'config' is not set"
+        )
+    return json.loads(config_str)''',
            "explanation": "Use .get() to check if the variable exists, then raise a descriptive error that helps with debugging.",
        },
    },
]

KEY_ERROR_NEGATIVE_EXAMPLES = [
    {
        "bad_fix": '''# DON'T DO THIS: Silent failure with None
def get_user_name(response):
    return response.get("data", {}).get("user_id")  # Returns None silently''',
        "why_bad": "Returning None silently hides the error and causes issues downstream when code expects a valid user_id.",
    },
    {
        "bad_fix": '''# DON'T DO THIS: Catch-all exception
def get_user_name(response):
    try:
        return response["data"]["user_id"]
    except:
        return None''',
        "why_bad": "Bare except catches everything including KeyboardInterrupt and SystemExit. Always catch specific exceptions.",
    },
    {
        "bad_fix": '''# DON'T DO THIS: Overly defensive with multiple try/except
def get_user_name(response):
    try:
        data = response["data"]
    except KeyError:
        return None
    try:
        return data["user_id"]
    except KeyError:
        return None''',
        "why_bad": "Excessive try/except blocks make code harder to read. Use .get() for cleaner optional access.",
    },
]
