"""Error troubleshooting — calls Simmer API with local fallback."""

import httpx

TROUBLESHOOT_URL = "https://api.simmer.markets/api/sdk/troubleshoot"

# Local fallback patterns (used when API is unreachable)
LOCAL_FALLBACK: list[dict] = [
    {
        "patterns": ["not enough balance", "insufficient balance", "insufficient funds"],
        "fix": "Check USDC.e balance with GET /api/sdk/portfolio. If balance is sufficient, run client.set_approvals().",
    },
    {
        "patterns": ["rate limit", "too many requests", "429"],
        "fix": "You're over the request limit. Use GET /api/sdk/briefing (1 call) instead of separate /context + /positions + /portfolio calls.",
    },
    {
        "patterns": ["nonce", "already used", "nonce too low"],
        "fix": "Nonce collision from concurrent trades. Serialize your trade calls or add a 2-3 second delay between trades.",
    },
]


def lookup_error(error_text: str) -> dict:
    """Call the Simmer troubleshoot API, fall back to local patterns if unreachable."""
    # Try the API first
    try:
        resp = httpx.post(
            TROUBLESHOOT_URL,
            json={"error_text": error_text},
            timeout=5,
        )
        if resp.status_code == 200:
            return resp.json()
    except httpx.HTTPError:
        pass

    # Local fallback
    lower = error_text.lower()
    for entry in LOCAL_FALLBACK:
        if any(p in lower for p in entry["patterns"]):
            return {"matched": True, "fix": entry["fix"]}
    return {
        "matched": False,
        "fix": "No known pattern matched. Check the full API docs at simmer.markets/docs.md or the quick reference at simmer.markets/skill.md.",
    }
