"""Unit test: adaptive size-partitioning covers the whole result pool, no gaps or dupes.

Stubs the GitHub API so no network calls are made. Run from the project root:
    venv/Scripts/python.exe tests/partition.py
"""
import os
import re
import sys
import random

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

POPULATION = 5432


def build_population():
    random.seed(1)
    pop = []
    for i in range(POPULATION):
        size = int(random.triangular(5, 3000, 120))  # skew small, like real .env files
        pop.append({"repository": {"full_name": f"u{i}/r"}, "path": f".env{i}",
                    "_size": size, "_id": i})
    return pop


def test_full_coverage():
    pop = build_population()

    def parse_range(q):
        mm = re.search(r"size:(\d+)\.\.(\d+)", q)
        return (int(mm.group(1)), int(mm.group(2))) if mm else (0, 10 ** 9)

    calls = {"n": 0}

    def fake_request_page(self, query, page):
        calls["n"] += 1
        lo, hi = parse_range(query)
        matches = [f for f in pop if lo <= f["_size"] <= hi]
        start = (page - 1) * 100
        return len(matches), matches[start:start + 100]

    m.GitHubKeyHunter._request_page = fake_request_page
    m.SEARCH_SLEEP = 0

    hunter = m.GitHubKeyHunter(token="x")
    items = hunter.search("gsk_ extension:env NOT is:fork")
    ids = [it["_id"] for it in items]

    assert len(set(ids)) == POPULATION, f"coverage {len(set(ids))}/{POPULATION}"
    assert len(ids) == len(set(ids)), f"{len(ids) - len(set(ids))} duplicates"
    print(f"OK: {len(set(ids))}/{POPULATION} files, 0 dupes, {calls['n']} API calls")


if __name__ == "__main__":
    test_full_coverage()
    print("partition passed")
