"""Common Simmer error patterns and fixes."""

ERROR_PATTERNS: 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() — the CLOB needs a one-time token approval before trading.",
    },
    {
        "patterns": ["rate limit", "too many requests", "429"],
        "fix": "You're over 18 req/min. Use GET /api/sdk/briefing (1 call) instead of calling /context + /positions + /portfolio separately. Briefing returns everything in one response.",
    },
    {
        "patterns": ["no liquidity", "not filled", "fak", "fill and kill"],
        "fix": "FAK order found no match at your price. Options: (1) Use order_type='GTC' for a limit order that sits on the book, (2) Adjust price closer to the market, (3) Reduce size.",
    },
    {
        "patterns": ["market is resolved", "resolved market", "cannot trade resolved"],
        "fix": "Can't trade resolved markets. If you won, call POST /api/sdk/redeem with the market_id to convert shares to USDC.e. Check GET /api/sdk/positions for positions with redeemable=true.",
    },
    {
        "patterns": ["minimum order", "below minimum", "min shares", "too small"],
        "fix": "Polymarket minimum is 5 shares (~$1-5 depending on price). Increase your amount. For $SIM trades there's no minimum.",
    },
    {
        "patterns": ["flip-flop", "discipline", "rapid reversal"],
        "fix": "The /context endpoint flagged a rapid position reversal (buying then selling quickly). Wait a cycle, or pass skip_safeguards=True in your trade request if you're sure.",
    },
    {
        "patterns": ["invalid side", "side must be"],
        "fix": 'Side must be "yes" or "no" (lowercase string, not boolean).',
    },
    {
        "patterns": ["missing shares", "shares required", "shares_sold"],
        "fix": "For sells, use the 'shares' param (not 'amount'). Get the exact value from GET /api/sdk/positions — use shares_yes or shares_no from the response.",
    },
    {
        "patterns": ["approval", "allowance", "not approved", "erc20"],
        "fix": "Run client.set_approvals() once before your first trade. This approves USDC.e and CTF tokens for the Polymarket exchange. Needs a small amount of POL for gas.",
    },
    {
        "patterns": ["nonce", "already used", "nonce too low", "replacement transaction"],
        "fix": "Nonce collision from concurrent trades. Serialize your trade calls (don't fire multiple trades in parallel) or add a 2-3 second delay between trades. The SDK handles nonce management if trades are sequential.",
    },
]


def lookup_error(error_text: str) -> dict:
    """Match an error message against known patterns and return a fix."""
    lower = error_text.lower()
    for entry in ERROR_PATTERNS:
        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.",
    }
