"""Integration test: POST /api/keys/recheck runs a real job thread that re-verifies stored
keys and promotes the workers. mongomock + stubbed check_keys; no network, no credits.

Run from the project root:
    venv/Scripts/python.exe -B tests/api_runs.py
"""
import os
import sys
import time

import mongomock
from fastapi.testclient import TestClient

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, ROOT)

os.environ["API_TOKEN"] = "test-token"
os.environ["MONGODB_URI"] = "mongodb://unused"

from keystore import MongoKeyStore
import api.db as db
import gh_key_hunter as hunter_mod

_coll = mongomock.MongoClient()["ai_key_hunt"]["keys"]
_store = MongoKeyStore(_collection=_coll)
db.get_store = lambda: _store
db.get_store.cache_clear = lambda: None  # type: ignore[attr-defined]
# _persist_to_store opens its own store; point it at the same in-memory collection.
hunter_mod.store_from_env = lambda: MongoKeyStore(_collection=_coll)


def fake_check_keys(keys, generate=True):
    assert generate is True
    working, not_working = [], []
    for item in keys:
        k = item["key"]
        if k.endswith("_ok"):
            working.append({"key": k, "status": "working", "provider": "Groq", "masked": k})
        elif k.endswith("_dead"):
            not_working.append({"key": k, "status": "dead", "provider": "Groq", "masked": k})
        else:
            not_working.append({"key": k, "status": "no_credits", "provider": "Groq", "masked": k})
    return {"working": working, "not_working": not_working}


hunter_mod.check_keys = fake_check_keys

from api.main import app

AUTH = {"Authorization": "Bearer test-token"}


def test_recheck_promotes_workers():
    _store.upsert_many([
        {"key": "gsk_a_ok", "provider_id": "groq", "masked": "gsk_a_ok", "category": "valid", "status": "no_credits"},
        {"key": "gsk_b_ok", "provider_id": "groq", "masked": "gsk_b_ok", "category": "valid", "status": "no_credits"},
        {"key": "gsk_c_nc", "provider_id": "groq", "masked": "gsk_c_nc", "category": "valid", "status": "no_credits"},
        {"key": "gsk_d_dead", "provider_id": "groq", "masked": "gsk_d_dead", "category": "valid", "status": "no_credits"},
    ], run="seed")
    assert _store.counts() == {"valid": 4}, _store.counts()

    with TestClient(app) as client:
        r = client.post("/api/keys/recheck", json={"category": "valid"}, headers=AUTH)
        assert r.status_code == 200, r.text
        rid = r.json()["run_id"]

        # Wait for the background job to finish (fast — check is stubbed).
        deadline = time.time() + 10
        status = None
        while time.time() < deadline:
            run = client.get(f"/api/runs/{rid}", headers=AUTH).json()
            status = run["status"]
            if status in ("done", "error", "stopped"):
                break
            time.sleep(0.2)
        assert status == "done", run

        assert run["counts"]["working"] == 2, run["counts"]
        assert run["kind"] == "recheck"
        # SSE history replays and ends with a terminal event.
        events = client.get(f"/api/runs/{rid}/events", headers=AUTH).text
        assert "\"type\": \"done\"" in events or "'type': 'done'" in events or "done" in events

    counts = _store.counts()
    assert counts.get("working") == 2, counts            # two promoted valid -> working
    assert counts.get("not_working") == 1, counts        # the _dead one
    assert counts.get("valid") == 1, counts              # the _nc one stays valid
    print(f"OK: recheck promoted 2 -> working, 1 -> not_working, 1 stayed valid | counts={counts}")


if __name__ == "__main__":
    test_recheck_promotes_workers()
    print("api_runs passed")
