"""Thread test: the search (producer) and check (consumer) threads cooperate correctly.

Stubs search to stream several slices and the download/check boundary, then runs the real
collect_phase1 (real threads, real queue) and asserts every slice was consumed, keys are
deduped across queries, and terminal vs candidate routing is correct. No network calls.
Run from the project root:
    venv/Scripts/python.exe tests/pipeline.py
"""
import os
import sys
import json
import tempfile

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)
import gh_key_hunter as m

# Each query streams two slices. Slice items are opaque here; fake_quickcheck reads a marker.
SLICES = {
    "q1": [
        [{"m": "gsk_live"}, {"m": "sk_dead"}],
        [{"m": "AIza_leak"}, {"m": "gsk_live"}],  # gsk_live repeats -> must dedupe
    ],
    "q2": [
        [{"m": "mist_nocred"}],
        [{"m": "sk_dead"}],                        # repeats across queries -> dedupe
    ],
}

# marker -> (key, quick status, which quick bucket)
KEYS = {
    "gsk_live": ("gsk_live1", "working", "working"),
    "sk_dead": ("sk_dead1", "dead", "not_working"),
    "AIza_leak": ("AIza_leak1", "leaked", "not_working"),
    "mist_nocred": ("mist_nocred1", "no_credits", "not_working"),
}


def fake_search(self, query, emit=None, cap=None):
    for sl in SLICES[query]:
        emit(sl)
    return []


def fake_quickcheck(self, items, seen_keys):
    working, not_working, meta = [], [], {}
    for it in items:
        key, status, bucket = KEYS[it["m"]]
        if key in seen_keys:
            continue
        seen_keys.add(key)
        meta[key] = {"provider_id": "p", "source": "s", "sources": ["s"], "variables": ["V"]}
        entry = {"key": key, "status": status, "sources": ["s"], "variables": ["V"]}
        (working if bucket == "working" else not_working).append(entry)
    return {"working": working, "not_working": not_working, "meta": meta}


def test_pipeline():
    m.GitHubKeyHunter.search = fake_search
    m.GitHubKeyHunter.quickcheck = fake_quickcheck

    hunter = m.GitHubKeyHunter(token="x")
    with tempfile.TemporaryDirectory() as d:
        rf = os.path.join(d, "run.json")
        candidates, dead, per_query = m.collect_phase1(hunter, ["q1", "q2"], rf)
        saved = json.load(open(rf))

    # gsk_live -> candidate; dead + leaked -> dead; mist_nocred (no_credits) -> candidate
    assert set(candidates) == {"gsk_live1", "mist_nocred1"}, set(candidates)
    assert {e["key"] for e in dead} == {"sk_dead1", "AIza_leak1"}, dead
    # dedupe: sk_dead and gsk_live each appear in two slices but once in results
    assert len(dead) == 2, [e["key"] for e in dead]
    # per-query quick buckets preserved for the productivity table
    assert per_query["q1"]["working"][0]["key"] == "gsk_live1"
    # quick-phase file: survivors live in `valid` (not yet generate-tested), working is empty
    assert saved["phase"] == "quick"
    assert saved["total"]["working"] == [], saved["total"]["working"]
    assert {e["key"] for e in saved["total"]["valid"]} == {"gsk_live1", "mist_nocred1"}
    print(f"OK: candidates={sorted(candidates)}  dead={sorted(e['key'] for e in dead)}")


if __name__ == "__main__":
    test_pipeline()
    print("pipeline passed")
