"""Integration test: phase 2 confirms only the survivors of phase 1.

Phase 1 (quick, list-only) filters out terminal failures (dead/leaked). Phase 2 (full,
chat-completion) runs only on the carried-forward candidates. Stubs phase 1's threaded
collector and the phase-2 check so no network calls are made and no credits are spent.
Run from the project root:
    venv/Scripts/python.exe tests/twophase.py
"""
import os
import sys
import json
import glob
import tempfile

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


def fake_collect_phase1(hunter, queries, results_file=None, *, on_event=None, stop_check=None, caps=None):
    # candidates = non-terminal survivors; dead = terminal (filtered in phase 1).
    candidates = {
        "gsk_valid1": {"key": "gsk_valid1", "provider_id": "groq", "source": "a/.env",
                       "sources": ["a/.env"], "variables": ["GROQ_API_KEY"]},
        "xai-restr1": {"key": "xai-restr1", "provider_id": "xai", "source": "d/.env",
                       "sources": ["d/.env"], "variables": ["XAI_API_KEY"]},
        "mist-nocred1": {"key": "mist-nocred1", "provider_id": "mistral", "source": "e/.env",
                         "sources": ["e/.env"], "variables": ["MISTRAL_API_KEY"]},
    }
    dead = [
        {"key": "sk-dead1", "status": "dead", "provider": "OpenAI"},
        {"key": "AIzaleak1", "status": "leaked", "provider": "Gemini"},
    ]
    per_query = {
        "q1": {"working": [{"key": "gsk_valid1", "status": "working"}],
               "not_working": [{"key": "sk-dead1", "status": "dead"},
                               {"key": "AIzaleak1", "status": "leaked"},
                               {"key": "xai-restr1", "status": "not_allowed"}]},
        "q2": {"working": [], "not_working": [{"key": "mist-nocred1", "status": "no_credits"}]},
    }
    return candidates, dead, per_query


def fake_check_keys(keys, generate=True):
    assert generate is True, "phase 2 must verify with generate=True"
    working, not_working = [], []
    for item in keys:
        k = item["key"]
        if k == "gsk_valid1":
            working.append({"key": k, "status": "working", "provider": "Groq"})
        elif k == "xai-restr1":
            not_working.append({"key": k, "status": "not_allowed", "provider": "Grok"})
        elif k == "mist-nocred1":
            not_working.append({"key": k, "status": "no_credits", "provider": "Mistral"})
        else:
            not_working.append({"key": k, "status": "dead", "provider": "?"})
    return {"working": working, "not_working": not_working}


def test_phase_routing():
    m.collect_phase1 = fake_collect_phase1
    m.check_keys = fake_check_keys
    m.store_from_env = lambda: None   # never touch the real MongoDB from a test
    m.GITHUB_TOKEN = "x"
    sys.argv = ["gh_key_hunter.py", "q1", "q2"]

    # Run in a throwaway cwd so main()'s results/ dir never lands in the project.
    with tempfile.TemporaryDirectory() as d:
        os.chdir(d)
        try:
            m.main()
            newfile = max(glob.glob("results/run_*.json"), key=os.path.getmtime)
            out = json.load(open(newfile))
        finally:
            os.chdir(ROOT)

    w = {e["key"] for e in out["total"]["working"]}
    valid = {e["key"] for e in out["total"]["valid"]}
    nw = {e["key"] for e in out["total"]["not_working"]}

    assert out["phase"] == "final", out["phase"]
    assert w == {"gsk_valid1"}, w                        # generated -> usable
    # authenticates but phase 2 couldn't confirm generation (restricted / no credits)
    assert valid == {"xai-restr1", "mist-nocred1"}, valid
    # only dead/leaked here -- valid-but-unusable keys no longer hide in this bucket
    assert nw == {"sk-dead1", "AIzaleak1"}, nw
    gv = next(e for e in out["total"]["working"] if e["key"] == "gsk_valid1")
    assert gv["variables"] == ["GROQ_API_KEY"], gv       # metadata carried onto final entry
    assert out["q1"]["working"][0]["key"] == "gsk_valid1"  # per-query quick buckets kept
    print(f"OK: working={sorted(w)}  valid={sorted(valid)}  not_working={sorted(nw)}")


if __name__ == "__main__":
    test_phase_routing()
    print("twophase passed")
