"""Check LLM API keys and split them into working and not working, without printing them.

Covers OpenAI, Claude (Anthropic), Gemini, Groq, Grok (xAI), Perplexity, DeepSeek, Mistral and
OpenRouter.
Stdlib only, Python 3.9+. Mistral keys have no prefix, so they're found only in a variable named
for Mistral (MISTRAL_API_KEY=...), or passed to check_key(key, "mistral").

As a script:
    python check_keys.py [PATH ...] [--keys K1,K2] [--json] [--quick] [--out DIR] [--reveal]

    PATH      .env or any text file, or a folder (scanned recursively); "-" reads stdin.
              With no PATH and no --keys, reads ./.env.
    --keys    keys given directly, comma separated.
    --json    print {"working": [...], "not_working": [...]} instead of text.
    --quick   only ask each provider to list models (free). No message is sent, so
              credits and quota go unchecked.
    --out     write working.json and not_working.json to DIR. These hold the full keys.
    --reveal  show full keys in the output instead of first 7 + last 4 characters.
    --workers how many keys to check at once (default 16).

As a function:
    import os, sys
    sys.path.insert(0, os.path.expanduser("~/.claude/skills/api-key-check"))
    from check_keys import check_keys, scrape_paths, scrape_text

    result = check_keys(["sk-...", "AIza..."])          # plain keys
    result = check_keys(scrape_paths(["E:/projects"]))   # every key found under a folder
    result["working"], result["not_working"]             # lists of dicts, full key under "key"
"""
from __future__ import annotations

import json
import os
import re
import sys
import urllib.error
import urllib.request
from concurrent.futures import ThreadPoolExecutor
from pathlib import Path

PROVIDERS = {
    "anthropic": {
        "name": "Claude", "names": ("ANTHROPIC", "CLAUDE"), "pattern": r"sk-ant-[A-Za-z0-9_\-]{20,}",
        "list": lambda k: ("https://api.anthropic.com/v1/models", {"x-api-key": k, "anthropic-version": "2023-06-01"}),
        "chat": lambda k: ("https://api.anthropic.com/v1/messages", {"x-api-key": k, "anthropic-version": "2023-06-01"},
                           {"model": "claude-haiku-4-5", "max_tokens": 16,
                            "messages": [{"role": "user", "content": "Reply OK."}]}),
    },
    # DeepSeek keys are sk- plus 32 lowercase hex; it must come before the broader OpenAI pattern.
    "deepseek": {
        "name": "DeepSeek", "names": ("DEEPSEEK",), "pattern": r"sk-[a-f0-9]{32}(?![A-Za-z0-9_\-])",
        "list": lambda k: ("https://api.deepseek.com/models", {"Authorization": f"Bearer {k}"}),
        "chat": lambda k: ("https://api.deepseek.com/chat/completions", {"Authorization": f"Bearer {k}"},
                           {"model": "deepseek-chat", "max_tokens": 16,
                            "messages": [{"role": "user", "content": "Reply OK."}]}),
    },
    # OpenRouter's model list is public, so /key (the key's own limits and usage) is the free check.
    "openrouter": {
        "name": "OpenRouter", "names": ("OPENROUTER",), "pattern": r"sk-or-[A-Za-z0-9_\-]{20,}",
        "list": lambda k: ("https://openrouter.ai/api/v1/key", {"Authorization": f"Bearer {k}"}),
        "chat": lambda k: ("https://openrouter.ai/api/v1/chat/completions", {"Authorization": f"Bearer {k}"},
                           {"model": "openai/gpt-4o-mini", "max_tokens": 16,
                            "messages": [{"role": "user", "content": "Reply OK."}]}),
    },
    "openai": {
        "name": "OpenAI", "names": ("OPENAI",), "pattern": r"sk-(?!ant-|or-)[A-Za-z0-9_\-]{20,}",
        "list": lambda k: ("https://api.openai.com/v1/models", {"Authorization": f"Bearer {k}"}),
        "chat": lambda k: ("https://api.openai.com/v1/chat/completions", {"Authorization": f"Bearer {k}"},
                           {"model": "gpt-4o-mini", "max_completion_tokens": 16,
                            "messages": [{"role": "user", "content": "Reply OK."}]}),
    },
    "gemini": {
        "name": "Gemini", "names": ("GEMINI", "GOOGLE_API", "GOOGLE_GENERATIVE", "GOOGLE_AI"),
        "pattern": r"AIza[0-9A-Za-z_\-]{35}",
        "list": lambda k: ("https://generativelanguage.googleapis.com/v1beta/models", {"x-goog-api-key": k}),
        "chat": lambda k: ("https://generativelanguage.googleapis.com/v1beta/models/gemini-3.5-flash-lite:generateContent",
                           {"x-goog-api-key": k},
                           {"contents": [{"parts": [{"text": "Reply OK."}]}], "generationConfig": {"maxOutputTokens": 16}}),
    },
    # Groq (gsk_ keys) is a different company from xAI's Grok.
    "groq": {
        "name": "Groq", "names": ("GROQ",), "pattern": r"gsk_[A-Za-z0-9]{20,}",
        "list": lambda k: ("https://api.groq.com/openai/v1/models", {"Authorization": f"Bearer {k}"}),
        "chat": lambda k: ("https://api.groq.com/openai/v1/chat/completions", {"Authorization": f"Bearer {k}"},
                           {"model": "llama-3.3-70b-versatile", "max_tokens": 16,
                            "messages": [{"role": "user", "content": "Reply OK."}]}),
    },
    "xai": {
        "name": "Grok", "names": ("XAI", "GROK"), "pattern": r"xai-[A-Za-z0-9]{20,}",
        "list": lambda k: ("https://api.x.ai/v1/models", {"Authorization": f"Bearer {k}"}),
        "chat": lambda k: ("https://api.x.ai/v1/chat/completions", {"Authorization": f"Bearer {k}"},
                           {"model": "grok-3", "max_tokens": 16,
                            "messages": [{"role": "user", "content": "Reply OK."}]}),
    },
    "perplexity": {
        "name": "Perplexity", "names": ("PERPLEXITY", "PPLX"), "pattern": r"pplx-[A-Za-z0-9]{20,}",
        "list": lambda k: ("https://api.perplexity.ai/v1/models", {"Authorization": f"Bearer {k}"}),
        "chat": lambda k: ("https://api.perplexity.ai/chat/completions", {"Authorization": f"Bearer {k}"},
                           {"model": "sonar", "max_tokens": 16,
                            "messages": [{"role": "user", "content": "Reply OK."}]}),
    },
    # Mistral keys have no prefix (32 letters and digits), so they're only found by variable name.
    "mistral": {
        "name": "Mistral", "names": ("MISTRAL",), "pattern": None,
        "list": lambda k: ("https://api.mistral.ai/v1/models", {"Authorization": f"Bearer {k}"}),
        "chat": lambda k: ("https://api.mistral.ai/v1/chat/completions", {"Authorization": f"Bearer {k}"},
                           {"model": "mistral-small-latest", "max_tokens": 16,
                            "messages": [{"role": "user", "content": "Reply OK."}]}),
    },
}

_KEY_RE = re.compile(r"(?<![A-Za-z0-9_\-])("
                     + "|".join(p["pattern"] for p in PROVIDERS.values() if p["pattern"]) + ")")
_ASSIGN_RE = re.compile(r"""^\s*(#?)\s*(?:export\s+|\$env:)?["']?([A-Za-z_][A-Za-z0-9_]*)["']?\s*[=:]\s*["']?([^\s"',#]+)""")
_PLACEHOLDER_RE = re.compile(r"your|xxxx|example|placeholder|\.\.\.|\*\*\*|<|>", re.I)
_SKIP_DIRS = {".git", "node_modules", "dist", "build", ".venv", "venv", "__pycache__", ".next", ".cache", "site-packages"}
_TEXT_SUFFIXES = {".env", ".txt", ".json", ".yaml", ".yml", ".toml", ".ini", ".cfg", ".conf", ".py", ".js", ".mjs",
                  ".cjs", ".ts", ".tsx", ".jsx", ".vue", ".md", ".ps1", ".sh", ".bat", ".cmd", ".properties", ".xml"}
_MAX_FILE_BYTES = 2_000_000

# status -> (verdict, action, counts as working)
_VERDICTS = {
    "working":       ("Working: a model answered", "keep", True),
    "valid":         ("Valid: the provider recognises it (credits not checked)", "keep; run without --quick to confirm credits", True),
    "model_missing": ("Valid: the test model isn't available to this key", "keep", True),
    "dead":          ("Dead: the provider doesn't recognise it", "dispose: remove it everywhere", False),
    "expired":       ("Expired: the key is past its expiry date", "dispose: remove it everywhere", False),
    "leaked":        ("Leaked: blocked by the provider after it was found exposed",
                      "dispose: delete it in the dashboard and find where it leaked", False),
    "no_credits":    ("Valid, no credits or quota on the account", "keep the key, fix billing", False),
    "rate_limited":  ("Valid, rate limited right now", "keep; try again later", False),
    "not_allowed":   ("Valid, not allowed to make this call", "check the key's restrictions in the dashboard", False),
    "provider_error": ("Provider trouble (5xx)", "try again later", False),
    "unreachable":   ("Could not reach the provider (says nothing about the key)", "retry", False),
    "unexpected":    ("Unexpected response", "look at the detail", False),
    "unknown_provider": ("Not checked: no provider matches this key",
                         "pass it as <PROVIDER>_API_KEY=<key>, or call check_key(key, provider_id)", False),
}


def mask(key: str) -> str:
    return f"{key[:7]}…{key[-4:]}" if len(key) > 12 else "…" + key[-4:]


def scrub(text: str) -> str:
    return _KEY_RE.sub("<key>", text)


def provider_for(key: str, name: str = "") -> str | None:
    """Provider from the key's prefix, else from the variable name it sits in. A DEEPSEEK
    variable also claims an sk- key that doesn't fit DeepSeek's usual shape."""
    by_key = next((pid for pid, p in PROVIDERS.items()
                   if p["pattern"] and re.fullmatch(p["pattern"], key)), None)
    by_name = next((pid for pid, p in PROVIDERS.items()
                    if any(n in name.upper() for n in p["names"])), None)
    if by_name and (by_key is None or (by_key == "openai" and by_name == "deepseek")):
        return by_name
    return by_key or by_name


def scrape_text(text: str, source: str = "") -> list[dict]:
    """Every API key in a block of text: anything with a known key prefix, plus
    values assigned to provider-named variables (FOO_API_KEY=..., commented or not)."""
    found = []
    for n, line in enumerate(text.lstrip("﻿").splitlines(), 1):
        where = f"{source}:{n}" if source else f"line {n}"
        a = _ASSIGN_RE.match(line)
        var, commented = (a.group(2), bool(a.group(1))) if a else ("", line.lstrip().startswith("#"))
        keys = {m.group(1) for m in _KEY_RE.finditer(line)}
        if a and a.group(3) not in keys and "KEY" in var.upper() and len(a.group(3)) >= 20 \
                and provider_for(a.group(3), var):
            keys.add(a.group(3))
        for key in keys:
            if _PLACEHOLDER_RE.search(key):
                continue
            found.append({"key": key, "provider_id": provider_for(key, var),
                          "source": where + (f" {var}" if var else "") + (" (commented out)" if commented else "")})
    return found


def scrape_paths(paths: list[str]) -> list[dict]:
    """Scrape files, and folders recursively (skipping .git, node_modules, builds and virtualenvs)."""
    found, files = [], []
    for raw in paths:
        if raw == "-":
            found += scrape_text(sys.stdin.read(), "stdin")
        elif Path(raw).is_file():
            files.append(raw)
        else:
            for dirpath, dirnames, filenames in os.walk(raw):
                dirnames[:] = [d for d in dirnames if d not in _SKIP_DIRS]   # never descend into them
                files += [os.path.join(dirpath, f) for f in filenames
                          if f.startswith(".env") or os.path.splitext(f)[1].lower() in _TEXT_SUFFIXES]

    def read(path: str) -> list[dict]:
        try:
            if os.path.getsize(path) <= _MAX_FILE_BYTES:
                with open(path, encoding="utf-8", errors="replace") as fh:
                    return scrape_text(fh.read(), path)
        except OSError:
            pass
        return []

    with ThreadPoolExecutor(max_workers=16) as pool:
        for hits in pool.map(read, files):
            found += hits
    return found


def _call(url: str, headers: dict, body: dict | None = None) -> tuple[int, str, dict, object]:
    """(status, error message, response headers, parsed JSON body on success)."""
    data = json.dumps(body).encode() if body is not None else None
    # Groq's Cloudflare rejects Python's default user agent (403 "error code: 1010").
    req = urllib.request.Request(url, data=data, headers={
        **headers, "Content-Type": "application/json", "User-Agent": "api-key-check/1.0"})
    try:
        with urllib.request.urlopen(req, timeout=20) as r:
            raw = r.read()
            try:
                parsed = json.loads(raw)
            except ValueError:
                parsed = None
            return r.status, "", dict(r.headers), parsed
    except urllib.error.HTTPError as e:
        raw = e.read().decode("utf-8", "replace")
        try:
            err = json.loads(raw)
            err = (err[0] if isinstance(err, list) else err).get("error", err)
            msg = err if isinstance(err, str) else " ".join(
                str(err.get(k)) for k in ("code", "type", "status", "message") if err.get(k))
        except Exception:
            msg = raw
        return e.code, scrub(msg)[:220], dict(e.headers or {}), None
    except Exception as e:  # network, DNS, timeout
        return 0, f"{type(e).__name__}: {scrub(str(e))[:160]}", {}, None


def _rate_limits(headers: dict) -> dict:
    """Rate-limit headroom from response headers (OpenAI, Groq, xAI, Mistral, Claude style)."""
    out = {}
    for name, val in headers.items():
        n = name.lower()
        if "ratelimit" not in n or "policy" in n:
            continue
        short = re.sub(r"^(x-ratelimit-|anthropic-ratelimit-|ratelimit-|x-)", "", n)
        out[short] = val
    return out


_NO_USAGE = {
    "openai": "spend and balance need an admin key; see platform.openai.com/usage",
    "anthropic": "spend and balance need an admin key; see console.anthropic.com",
    "gemini": "Google exposes no usage to API keys; see aistudio.google.com (Usage, Rate limits)",
    "groq": "no balance endpoint; see console.groq.com",
    "perplexity": "no balance endpoint; see perplexity.ai/account/api",
    "mistral": "no balance endpoint; see console.mistral.ai",
}


def _usage(pid: str, key: str, listed_body: object) -> dict:
    """Balance, spend, limits and expiry the provider reports for this key, where it reports any."""
    auth = {"Authorization": f"Bearer {key}"}
    if pid == "openrouter":
        d = (listed_body or {}).get("data", {}) if isinstance(listed_body, dict) else {}
        wanted = ("label", "usage", "usage_daily", "usage_weekly", "usage_monthly", "limit",
                  "limit_remaining", "limit_reset", "is_free_tier", "expires_at")
        info = {k: d[k] for k in wanted if k in d}
        if "usage" in info:
            info["usage"] = f"${info['usage']:.4f} spent" if isinstance(info["usage"], (int, float)) else info["usage"]
        if info.get("limit") is None and "limit" in info:
            info["limit"] = "no spending limit"
        info.setdefault("expires_at", "not set")
        return info
    if pid == "deepseek":
        code, _, _, body = _call("https://api.deepseek.com/user/balance", auth)
        if code == 200 and isinstance(body, dict):
            bal = [f"{b.get('total_balance')} {b.get('currency')}" for b in body.get("balance_infos", [])]
            return {"balance": ", ".join(bal) or "0", "is_available": body.get("is_available")}
        return {}
    if pid == "xai":
        code, _, _, body = _call("https://api.x.ai/v1/api-key", auth)
        if code == 200 and isinstance(body, dict):
            wanted = ("name", "create_time", "modify_time", "api_key_blocked", "api_key_disabled", "team_blocked")
            return {k: body[k] for k in wanted if k in body}
        return {}
    return {"note": _NO_USAGE[pid]} if pid in _NO_USAGE else {}


def _model_count(listed_body: object) -> "int | None":
    """How many models the key can access — a capability proxy that works for every provider.

    OpenAI-style lists put them under `data`, Gemini under `models`. OpenRouter's list endpoint
    is `/key` (key info, not a model array), so it has no count here.
    """
    if not isinstance(listed_body, dict):
        return None
    for field in ("data", "models"):
        arr = listed_body.get(field)
        if isinstance(arr, list):
            return len(arr)
    return None


def _status(code: int, msg: str) -> str:
    t = msg.lower()
    if code == 0 or "error code: 10" in t:      # Cloudflare block page, not the API
        return "unreachable"
    if re.search(r"leaked|compromised", t):
        return "leaked"
    if re.search(r"expired", t):
        return "expired"
    if code == 401 or re.search(r"invalid.api.key|incorrect api key|api key not valid|invalid x-api-key|"
                                r"authentication_error|api_key_invalid|unauthenticated|expired_api_key", t):
        return "dead"
    if code == 402 or re.search(r"insufficient_quota|insufficient credits|credit balance|billing|"
                                r"exceeded your current quota|payment|no credits", t):
        return "no_credits"
    if code == 429:
        return "rate_limited"
    if code == 403:
        return "not_allowed"
    if code == 404 or re.search(r"model_not_found|not_found|does not exist|is not found", t):
        return "model_missing"
    if code >= 500:
        return "provider_error"
    return "unexpected"


def check_key(key: str, provider_id: str | None = None, *, generate: bool = True) -> dict:
    """Check one key. Returns provider, status, verdict, action, working, detail, and `usage`
    (balance, spend, limits, expiry and rate-limit headroom, whatever the provider reports)."""
    pid = provider_id or provider_for(key)
    out = {"key": key, "masked": mask(key), "provider_id": pid,
           "provider": PROVIDERS[pid]["name"] if pid else "Unknown"}
    usage: dict = {}
    if not pid:
        status, detail = "unknown_provider", "no known provider prefix (sk-, sk-ant-, sk-or-, AIza, gsk_, xai-, pplx-); for a Mistral key use MISTRAL_API_KEY=..."
    else:
        p = PROVIDERS[pid]
        code, detail, headers, listed = _call(*p["list"](key))
        if code == 404:   # no models endpoint for this key: only a message can tell
            generate = True
            code, detail = 200, ""
        if code != 200:
            status = _status(code, detail)
        elif not generate:
            status = "valid"
        else:
            code, detail, headers, _ = _call(*p["chat"](key))
            status = "working" if code == 200 else _status(code, detail)
        if status not in ("dead", "expired", "leaked", "unreachable"):
            usage = _usage(pid, key, listed)
            limits = _rate_limits(headers)
            if limits:
                usage["rate_limits"] = limits
            models = _model_count(listed)
            if models is not None:
                usage["models"] = models
    verdict, action, working = _VERDICTS[status]
    return {**out, "status": status, "verdict": verdict, "action": action, "working": working,
            "detail": detail, "usage": usage}


def check_keys(keys, *, generate: bool = True, workers: int = 16) -> dict:
    """Check many keys at once and split them into working and not working.

    `keys` may be plain strings or dicts from scrape_text / scrape_paths. Duplicates
    are checked once; every place a key was found is kept under "sources".
    """
    items = []
    for item in keys:
        # A string that's a NAME=value line or holds keys inside other text is scraped first.
        scraped = scrape_text(item) if isinstance(item, str) and re.search(r"[=:\s]", item.strip()) else []
        items += scraped or [{"key": item} if isinstance(item, str) else dict(item)]
    merged: dict[str, dict] = {}
    for item in items:
        key = item["key"].strip().strip("\"'")
        if not key:
            continue
        entry = merged.setdefault(key, {"provider_id": item.get("provider_id"), "sources": []})
        entry["provider_id"] = entry["provider_id"] or item.get("provider_id")
        if item.get("source"):
            entry["sources"].append(item["source"])
    with ThreadPoolExecutor(max_workers=max(1, workers)) as pool:
        results = list(pool.map(
            lambda kv: {**check_key(kv[0], kv[1]["provider_id"], generate=generate), "sources": kv[1]["sources"]},
            merged.items()))
    return {"working": [r for r in results if r["working"]],
            "not_working": [r for r in results if not r["working"]]}


def _public(entry: dict, reveal: bool) -> dict:
    return entry if reveal else {k: v for k, v in entry.items() if k != "key"}


def main(argv: list[str]) -> int:
    flags = {a for a in argv if a in ("--json", "--quick", "--reveal")}
    rest = [a for a in argv if a not in flags]
    keys_arg, out_dir, paths, workers, i = [], None, [], 16, 0
    while i < len(rest):
        if rest[i] == "--workers" and i + 1 < len(rest):
            workers = int(rest[i + 1])
            i += 2
        elif rest[i] == "--keys" and i + 1 < len(rest):
            keys_arg += [k for k in rest[i + 1].split(",") if k.strip()]
            i += 2
        elif rest[i] == "--out" and i + 1 < len(rest):
            out_dir = rest[i + 1]
            i += 2
        else:
            paths.append(rest[i])
            i += 1
    if not paths and not keys_arg:
        paths = [".env"]
    missing = [p for p in paths if p != "-" and not Path(p).exists()]
    if missing:
        print(f"Not found: {', '.join(missing)}")
        return 1

    found = scrape_paths(paths)
    for k in keys_arg:
        found += scrape_text(k, "--keys") or [{"key": k, "source": "--keys"}]
    if not found:
        print(json.dumps({"working": [], "not_working": []}) if "--json" in flags else "No API keys found.")
        return 0
    result = check_keys(found, generate="--quick" not in flags, workers=workers)
    reveal = "--reveal" in flags

    if out_dir:
        Path(out_dir).mkdir(parents=True, exist_ok=True)
        for bucket in ("working", "not_working"):
            (Path(out_dir) / f"{bucket}.json").write_text(json.dumps(result[bucket], indent=2), encoding="utf-8")

    if "--json" in flags:
        print(json.dumps({b: [_public(e, reveal) for e in result[b]] for b in result}, indent=2, ensure_ascii=False))
        return 0

    total = len(result["working"]) + len(result["not_working"])
    how = "listed models only, credits not checked" if "--quick" in flags else "one tiny message each"
    print(f"Checked {total} key(s) ({how})")
    for bucket, title in (("working", "WORKING"), ("not_working", "NOT WORKING")):
        print(f"\n{title} ({len(result[bucket])})")
        for e in result[bucket]:
            src = e["sources"][0] if e["sources"] else ""
            if len(e["sources"]) > 1:
                src += f" (+{len(e['sources']) - 1} more)"
            print(f"  {e['provider']:<7} {e['key'] if reveal else e['masked']}  {e['verdict']}  ->  {e['action']}")
            if src:
                print(f"          found at {src}")
            if e["detail"] and not e["working"]:
                print(f"          {e['detail']}")
            usage = {k: v for k, v in e.get("usage", {}).items() if k != "rate_limits"}
            if usage:
                print("          usage: " + ", ".join(f"{k} {v}" if k != "note" else str(v) for k, v in usage.items()))
            limits = e.get("usage", {}).get("rate_limits")
            if limits:
                print("          rate limits: " + ", ".join(f"{k} {v}" for k, v in limits.items()))
    if out_dir:
        print(f"\nWrote working.json and not_working.json to {out_dir} (they contain the full keys).")
    return 0


if __name__ == "__main__":
    sys.exit(main(sys.argv[1:]))
