"""Apply the qualifying rule (qualify-r1.json with Change 1) to every repository code search returned.

Stages, each resumable (one JSONL row per repository per stage, in the output folder):
  meta    GraphQL, in batches: fork, description, topics, and the text of each candidate dbt_project.yml (c1, c2, c3)
  tree    GraphQL, in batches: the model and seed folders of each candidate project, and integration_tests (c4, c6, c7)
  contrib REST contributors API, one call per repository still in (c5)
then `decide` writes qualifying.json and exclusions.json.

Usage:
  python3 -B screen.py <enum_dir> <out_dir> <stage> [--budget N] [--companies <a private CSV with a company column>] [--maker-orgs <private JSON>]
The company list and the tool maker's logins are private and read only from the paths given; neither is written to
the outputs.
"""
import csv
import glob
import json
import os
import posixpath
import random
import re
import subprocess
import sys
import time
import urllib.error
import urllib.request

HERE = os.path.dirname(os.path.abspath(__file__))
RULE = json.load(open(os.path.join(HERE, "..", "public-rule", "qualify-r1.json"), encoding="utf-8"))
EXCLUDED_DIRS = ("dbt_packages", "dbt_modules", "target", "integration_tests", "site-packages")
PACKAGE_DIRS = {"include", "tests", "test", "fixtures", "samples", "examples", "example"}
MAKER_ORGS = set()  # the tool maker's logins, read with --maker-orgs from a private file (clause c2)
MAX_CANDIDATES = 6
DEPTH = 8
GQL = "https://api.github.com/graphql"


def token():
    return subprocess.run(["gh", "auth", "token"], capture_output=True, text=True, check=True).stdout.strip()


def http(tok, url, body=None):
    data = json.dumps(body).encode() if body is not None else None
    req = urllib.request.Request(url, data=data, headers={
        "Authorization": f"Bearer {tok}", "Accept": "application/vnd.github+json",
        "X-GitHub-Api-Version": "2022-11-28", "User-Agent": "public-project-audit"})
    transport = 0
    for attempt in range(8):
        try:
            with urllib.request.urlopen(req, timeout=90) as r:
                return r.status, dict(r.headers), json.load(r)
        except urllib.error.HTTPError as e:
            if e.code in (403, 429) and e.headers.get("X-RateLimit-Remaining") == "0":
                wait = max(int(e.headers.get("X-RateLimit-Reset") or 0) - int(time.time()) + 5, 5)
                print(f"hourly limit reached, waiting {wait} for the reset", flush=True)
                time.sleep(min(wait, 3700))
                continue
            if e.code in (403, 429) and ("rate limit" in (e.read() or b"").decode("utf-8", "replace").lower()
                                         or e.headers.get("Retry-After")):
                wait = int(e.headers.get("Retry-After") or 60)
                print(f"rate limited, waiting {wait}", flush=True)
                time.sleep(min(wait, 300))
                continue
            if e.code in (502, 503, 504):
                time.sleep(10 * (attempt + 1))
                continue
            try:
                payload = json.loads(e.read() or b"{}")
            except Exception:
                payload = {}
            return e.code, dict(e.headers), payload
        except (urllib.error.URLError, TimeoutError, ConnectionError, OSError) as e:
            transport += 1
            print(f"transport error {e!r}, retry", flush=True)
            if transport >= 3:
                return 0, {}, {}  # the caller retries smaller or records an error
            time.sleep(10)
    return 0, {}, {}


SCREEN_SEED = 20261111
SCREEN_N = 10000
SUBSET_ONLY = False


def screen_order(repos):
    """Change 3: the screening sample is the first SCREEN_N ids of a seeded shuffle of all frame ids, in that order"""
    ids = sorted(repos)
    random.Random(SCREEN_SEED).shuffle(ids)
    return ids


def norm(s):
    return re.sub(r"[^a-z0-9]", "", (s or "").lower())


def tokens(s):
    return set(t for t in re.split(r"[^a-z0-9]+", (s or "").lower()) if t)


def load_candidates(enum_dir):
    """repo_id -> {full_name, owner, fork, paths}"""
    repos = {}
    for line in open(os.path.join(enum_dir, "pages.jsonl"), encoding="utf-8"):
        try:
            rec = json.loads(line)
        except ValueError:
            continue
        for it in rec["items"]:
            r = repos.setdefault(it["repo_id"], {"repo_id": it["repo_id"], "full_name": it["full_name"],
                                                 "owner": it["owner"], "fork": it["fork"], "paths": set()})
            r["paths"].add(it["path"])
    for r in repos.values():
        r["all_paths"] = sorted(r["paths"])
        cands = [p for p in r["all_paths"] if posixpath.basename(p) == "dbt_project.yml"
                 and not any(seg in EXCLUDED_DIRS for seg in p.split("/")[:-1])]
        r["candidates"] = sorted(cands, key=lambda p: (len(p), p))[:MAX_CANDIDATES]
        del r["paths"]
    return repos


SHARD = (0, 1)


def done_ids(path):
    """rows of a stage from its file and every shard file beside it (path-<k>.jsonl)"""
    out = {}
    base = path[:-len(".jsonl")]
    files = [path] + sorted(glob.glob(base + "-*.jsonl"))
    for fp in files:
        if os.path.exists(fp):
            for line in open(fp, encoding="utf-8"):
                if line.strip():
                    row = json.loads(line)
                    out[row["repo_id"]] = row
    return out


def shard_path(path):
    k, n = SHARD
    return path if n == 1 else path[:-len(".jsonl")] + f"-{k}.jsonl"


def in_shard(rid):
    k, n = SHARD
    return rid % n == k


def append(path, rows):
    with open(path, "a", encoding="utf-8") as f:
        for row in rows:
            f.write(json.dumps(row) + "\n")
        f.flush()
        os.fsync(f.fileno())


def gql_str(s):
    return json.dumps(s)


def parse_project_yml(text):
    """model and seed folders from dbt_project.yml text; falls back to defaults and a line scan."""
    model_paths, seed_paths = None, None
    try:
        import yaml
        d = yaml.safe_load(text)
        if isinstance(d, dict):
            model_paths = d.get("model-paths") or d.get("source-paths")
            seed_paths = d.get("seed-paths") or d.get("data-paths")
    except Exception:
        for key, var in (("model-paths", "m"), ("source-paths", "m"), ("seed-paths", "s"), ("data-paths", "s")):
            m = re.search(r"^" + key + r"\s*:\s*\[([^\]]*)\]", text or "", re.M)
            if m:
                vals = [v.strip().strip("'\"") for v in m.group(1).split(",") if v.strip()]
                if var == "m" and model_paths is None:
                    model_paths = vals
                if var == "s" and seed_paths is None:
                    seed_paths = vals
    def clean(v, default):
        if isinstance(v, str):
            v = [v]
        if not isinstance(v, list):
            return default
        v = [str(x).strip().strip("/") for x in v if isinstance(x, (str, int)) and str(x).strip()]
        return [x for x in v if ".." not in x and "{{" not in x] or default
    return clean(model_paths, ["models"]), clean(seed_paths, ["seeds", "data"])


def tree_fragment(depth):
    if depth == 0:
        return "entries { name type }"
    return "entries { name type object { ... on Tree { " + tree_fragment(depth - 1) + " } } }"


def walk(entries, prefix=""):
    """yield (relative path, type) for every entry in a nested GraphQL tree"""
    for e in entries or []:
        p = f"{prefix}{e['name']}"
        yield p, e["type"]
        obj = e.get("object") or {}
        if e["type"] == "tree" and obj.get("entries") is not None:
            yield from walk(obj["entries"], p + "/")


# ---------------- stage: meta ----------------
def stage_meta(repos, out, tok, budget, companies):
    path = os.path.join(out, "meta.jsonl")
    have = done_ids(path)
    order = screen_order(repos)  # the screening sample first (Change 3), then the rest of the frame
    if SUBSET_ONLY:
        order = order[:SCREEN_N]
    todo = [repos[rid] for rid in order if rid not in have and in_shard(rid)]
    print(f"meta: {len(have)} done, {len(todo)} to do", flush=True)
    t0 = time.time()
    batch = 25
    for i in range(0, len(todo), batch):
        if time.time() - t0 > budget:
            print("CHUNK_DONE meta", flush=True)
            return
        part = todo[i:i + batch]
        q = []
        for j, r in enumerate(part):
            owner, name = r["full_name"].split("/", 1)
            ys = " ".join(f'y{k}: object(expression: {gql_str("HEAD:" + p)}) {{ ... on Blob {{ text byteSize }} }}'
                          for k, p in enumerate(r["candidates"]))
            q.append(f'r{j}: repository(owner: {gql_str(owner)}, name: {gql_str(name)}) {{ databaseId isFork isArchived '
                     f'stargazerCount pushedAt createdAt description owner {{ login __typename }} '
                     f'repositoryTopics(first: 20) {{ nodes {{ topic {{ name }} }} }} {ys} }}')
        status, _, res = http(tok, GQL, {"query": "query { " + " ".join(q) + " }"})
        if not res.get("data"):
            print(f"graphql status {status}; skipping batch for a later rerun", flush=True)
            time.sleep(30)
            continue
        data = res.get("data") or {}
        rows = []
        for j, r in enumerate(part):
            d = data.get(f"r{j}")
            row = {"repo_id": r["repo_id"], "full_name": r["full_name"], "owner": r["owner"]}
            if d is None:
                row["gone"] = True
            else:
                row.update({"fork": d["isFork"], "archived": d["isArchived"], "stars": d["stargazerCount"],
                            "pushed": d["pushedAt"], "created": d["createdAt"], "description": d["description"],
                            "topics": [n["topic"]["name"] for n in d["repositoryTopics"]["nodes"]],
                            "owner_type": d["owner"]["__typename"],
                            "ymls": {p: (d.get(f"y{k}") or {}).get("text") for k, p in enumerate(r["candidates"])}})
            rows.append(row)
        append(shard_path(path), rows)
    print("STAGE_COMPLETE meta", flush=True)


def clause_meta(r, m, companies):
    if m.get("gone"):
        return "gone"
    if m["fork"] or r["fork"]:
        return "c1_fork"
    o = norm(m["owner"])
    if o in MAKER_ORGS or any((len(c) >= 4 and c in o) or (len(c) < 4 and c == o) for c in companies):
        return "c2_owner_listed"
    name = m["full_name"].split("/", 1)[1]
    name_topics = " ".join([name] + m["topics"])
    desc = m.get("description") or ""
    if tokens(name_topics) & set(RULE["tutorial_tokens"]) or tokens(desc) & set(RULE["description_tokens"]):
        return "c3_tutorial"
    joined = (name_topics + " " + desc).lower()
    if any(s in joined for s in RULE["tutorial_substrings"]):
        return "c3_tutorial"
    return None


# ---------------- stage: tree ----------------
def stage_tree(repos, out, tok, budget, companies):
    meta = done_ids(os.path.join(out, "meta.jsonl"))
    path = os.path.join(out, "tree.jsonl")
    have = done_ids(path)
    todo = []
    for rid in screen_order(repos)[:SCREEN_N]:
        m = meta.get(rid)
        if m is None:
            continue
        r = repos[rid]
        if rid in have or not in_shard(rid) or clause_meta(r, m, companies):
            continue
        todo.append((r, m))
    print(f"tree: {len(have)} done, {len(todo)} to do", flush=True)
    t0 = time.time()
    batch = 10
    chunks = [todo[i:i + batch] for i in range(0, len(todo), batch)]
    while chunks:
        if time.time() - t0 > budget:
            print("CHUNK_DONE tree", flush=True)
            return
        part = chunks.pop(0)
        q, plan = [], []
        for j, (r, m) in enumerate(part):
            owner, name = r["full_name"].split("/", 1)
            fields = ['it: object(expression: "HEAD:integration_tests") { ... on Tree { entries { name } } }']
            spec = []
            for k, p in enumerate(r["candidates"]):
                pdir = posixpath.dirname(p)
                mp, sp = parse_project_yml(m["ymls"].get(p) or "")
                for a, folder in enumerate(mp[:4]):
                    full = posixpath.join(pdir, folder) if pdir else folder
                    fields.append(f'm{k}_{a}: object(expression: {gql_str("HEAD:" + full)}) {{ ... on Tree {{ {tree_fragment(DEPTH)} }} }}')
                for a, folder in enumerate(sp[:2]):
                    full = posixpath.join(pdir, folder) if pdir else folder
                    fields.append(f's{k}_{a}: object(expression: {gql_str("HEAD:" + full)}) {{ ... on Tree {{ {tree_fragment(2)} }} }}')
                spec.append({"path": p, "model_paths": mp[:4], "seed_paths": sp[:2]})
            q.append(f'r{j}: repository(owner: {gql_str(owner)}, name: {gql_str(name)}) {{ {" ".join(fields)} }}')
            plan.append(spec)
        status, _, res = http(tok, GQL, {"query": "query { " + " ".join(q) + " }"})
        data = res.get("data") or {}
        if not data:
            if len(part) > 1:
                print(f"graphql status {status} on a batch of {len(part)}; retrying one at a time", flush=True)
                chunks[:0] = [[x] for x in part]
            else:
                print(f"graphql status {status} on a single repository; recorded as an error", flush=True)
                append(shard_path(path), [{"repo_id": part[0][0]["repo_id"], "tree_error": True}])
            time.sleep(5)
            continue
        rows = []
        for j, (r, m) in enumerate(part):
            d = data.get(f"r{j}")
            row = {"repo_id": r["repo_id"]}
            if d is None:
                row["gone"] = True
                rows.append(row)
                continue
            it = d.get("it") or {}
            row["integration_tests_project"] = any(e["name"] == "dbt_project.yml" for e in it.get("entries") or [])
            projects = []
            for k, spec in enumerate(plan[j]):
                models, seeds = [], []
                for a, _ in enumerate(spec["model_paths"]):
                    t = d.get(f"m{k}_{a}") or {}
                    models += [p for p, typ in walk(t.get("entries")) if typ == "blob" and p.endswith((".sql", ".py"))]
                for a, _ in enumerate(spec["seed_paths"]):
                    t = d.get(f"s{k}_{a}") or {}
                    seeds += [p for p, typ in walk(t.get("entries")) if typ == "blob"]
                names = {posixpath.splitext(posixpath.basename(p))[0] for p in models + seeds}
                projects.append({"path": spec["path"], "model_paths": spec["model_paths"], "models": len(models),
                                 "tutorial_seeds": {"raw_customers", "raw_orders", "raw_payments"} <= names})
            row["projects"] = projects
            rows.append(row)
        append(shard_path(path), rows)
    print("STAGE_COMPLETE tree", flush=True)


def stage_rtree(repos, out, tok, budget, companies):
    """Change 4: the same rows as stage_tree, read from the REST recursive git tree (one call per repository)."""
    meta = done_ids(os.path.join(out, "meta.jsonl"))
    path = os.path.join(out, "tree.jsonl")
    have = done_ids(path)
    todo = []
    for rid in screen_order(repos)[:SCREEN_N]:
        m = meta.get(rid)
        if m is None or rid in have or not in_shard(rid) or clause_meta(repos[rid], m, companies):
            continue
        todo.append((repos[rid], m))
    print(f"rtree: {len(have)} done, {len(todo)} to do", flush=True)
    t0 = time.time()
    for r, m in todo:
        if time.time() - t0 > budget:
            print("CHUNK_DONE rtree", flush=True)
            return
        status, _, res = http(tok, f"https://api.github.com/repositories/{r['repo_id']}/git/trees/HEAD?recursive=1")
        row = {"repo_id": r["repo_id"], "via": "rest"}
        if status in (404, 409, 451):  # gone, empty or blocked
            row["gone"] = True
            append(shard_path(path), [row])
            continue
        if status != 200 or not isinstance(res, dict) or "tree" not in res:
            print(f"status {status}; left for a rerun", flush=True)  # never recorded as a result
            continue
        if res.get("truncated"):
            continue  # left for the GraphQL listing (stage tree), as Change 4 says
        blobs = [e["path"] for e in res["tree"] if e.get("type") == "blob"]
        row["integration_tests_project"] = "integration_tests/dbt_project.yml" in set(blobs)
        projects = []
        for p in r["candidates"]:
            pdir = posixpath.dirname(p)
            mp, sp = parse_project_yml(m["ymls"].get(p) or "")
            mp, sp = mp[:4], sp[:2]
            models, seeds = [], []
            for folder in mp:
                base = (posixpath.join(pdir, folder) if pdir else folder).strip("/") + "/"
                models += [b for b in blobs if b.startswith(base) and b.endswith((".sql", ".py"))
                           and b[len(base):].count("/") <= DEPTH]
            for folder in sp:
                base = (posixpath.join(pdir, folder) if pdir else folder).strip("/") + "/"
                seeds += [b for b in blobs if b.startswith(base) and b[len(base):].count("/") <= 2]
            names = {posixpath.splitext(posixpath.basename(b))[0] for b in models + seeds}
            projects.append({"path": p, "model_paths": mp, "models": len(set(models)),
                             "tutorial_seeds": {"raw_customers", "raw_orders", "raw_payments"} <= names})
        row["projects"] = projects
        append(shard_path(path), [row])
    print("STAGE_COMPLETE rtree", flush=True)


def choose(tree_row):
    ps = tree_row.get("projects") or []
    if not ps:
        return None
    return sorted(ps, key=lambda p: (-p["models"], len(p["path"]), p["path"]))[0]


def clause_tree(t, r=None):
    if t.get("gone"):
        return "gone"
    if t.get("tree_error"):
        return "error"
    p = choose(t)
    if p is None:
        return "c6_models"
    segs = set(p["path"].split("/")[:-1])
    def own_it(q):  # Change 2: an integration_tests folder inside an ignored folder is an installed copy, not this repo's
        segs = q.split("/")[:-1]
        return "integration_tests" in segs and not set(segs[:segs.index("integration_tests")]) & set(EXCLUDED_DIRS)
    it_paths = any(own_it(q) for q in (r or {}).get("all_paths", []))
    if t.get("integration_tests_project") or it_paths or segs & PACKAGE_DIRS:
        return "c4_package"
    if p["models"] < 20:
        return "c6_models"
    if p["tutorial_seeds"]:
        return "c7_tutorial_seeds"
    return None


# ---------------- stage: contrib ----------------
def stage_contrib(repos, out, tok, budget, companies):
    meta = done_ids(os.path.join(out, "meta.jsonl"))
    tree = done_ids(os.path.join(out, "tree.jsonl"))
    path = os.path.join(out, "contrib.jsonl")
    have = done_ids(path)
    todo = [rid for rid in screen_order(repos)[:SCREEN_N] if rid in tree and rid not in have and in_shard(rid)
            and not clause_meta(repos[rid], meta[rid], companies) and not clause_tree(tree[rid], repos[rid])]
    print(f"contrib: {len(have)} done, {len(todo)} to do", flush=True)
    t0 = time.time()
    for rid in todo:
        if time.time() - t0 > budget:
            print("CHUNK_DONE contrib", flush=True)
            return
        full = repos[rid]["full_name"]
        status, headers, res = http(tok, f"https://api.github.com/repositories/{rid}/contributors?per_page=100")
        row = {"repo_id": rid, "status": status}
        if status == 200 and isinstance(res, list):
            people = [c for c in res if c.get("type") != "Bot" and not str(c.get("login", "")).endswith("[bot]")]
            row["contributors"] = len(people)
            row["more_pages"] = 'rel="next"' in (headers.get("Link") or headers.get("link") or "")
        elif status == 204:
            row["contributors"] = 0
        elif status == 403 and "too large" in json.dumps(res).lower():
            row["contributors"] = None
            row["too_large"] = True
        elif status in (404, 451):
            row["gone"] = True
        else:
            row["error"] = True
        append(shard_path(path), [row])
        time.sleep(0.2)
    print("STAGE_COMPLETE contrib", flush=True)


def clause_contrib(c):
    if c.get("gone"):
        return "gone"
    if c.get("error"):
        return "error"
    if c.get("too_large") or c.get("more_pages"):
        return None
    return "c5_contributors" if (c.get("contributors") or 0) < 2 else None


# ---------------- decide ----------------
def wilson(k, n, z=1.96):
    if n == 0:
        return None, None
    ph = k / n
    d = 1 + z * z / n
    c = (ph + z * z / (2 * n)) / d
    h = z * ((ph * (1 - ph) / n + z * z / (4 * n * n)) ** 0.5) / d
    return c - h, c + h


def decide(repos, out, companies):
    meta = done_ids(os.path.join(out, "meta.jsonl"))
    tree = done_ids(os.path.join(out, "tree.jsonl"))
    contrib = done_ids(os.path.join(out, "contrib.jsonl"))
    meta_order = ["gone", "c1_fork", "c2_owner_listed", "c3_tutorial"]
    frame = {k: 0 for k in meta_order}
    unread = 0
    passed_meta = 0
    for rid, r in repos.items():
        m = meta.get(rid)
        if m is None:
            unread += 1
            continue
        c = clause_meta(r, m, companies)
        if c:
            frame[c] += 1
        else:
            passed_meta += 1
    order = meta_order + ["c4_package", "c6_models", "c7_tutorial_seeds", "c5_contributors", "error"]
    counts = {k: 0 for k in order}
    unscreened = 0
    qualifying = []
    subset = screen_order(repos)[:SCREEN_N]
    for rid in subset:
        r = repos[rid]
        m = meta.get(rid)
        if m is None:
            unscreened += 1
            continue
        c = clause_meta(r, m, companies)
        if c is None:
            t = tree.get(rid)
            if t is None:
                unscreened += 1
                continue
            c = clause_tree(t, r)
            if c is None:
                k = contrib.get(rid)
                if k is None:
                    unscreened += 1
                    continue
                c = clause_contrib(k)
                if c is None:
                    p = choose(t)
                    qualifying.append({"repo_id": rid, "full_name": r["full_name"], "owner": m["owner"],
                                       "project_path": p["path"], "model_paths": p["model_paths"],
                                       "models_in_tree": p["models"]})
        if c is not None:
            counts[c] += 1
    screened = len(subset) - unscreened
    screened_passed_meta = screened - sum(counts[k] for k in meta_order)
    lo, hi = wilson(len(qualifying), screened_passed_meta)
    rate = len(qualifying) / screened_passed_meta if screened_passed_meta else None
    summary = {"repositories_in_frame": len(repos), "frame_unread": unread,
               "frame_excluded_by_metadata_clause": frame, "frame_passed_metadata_clauses": passed_meta,
               "screening_sample": {"seed": SCREEN_SEED, "size": len(subset), "screened": screened,
                                    "not_screened": unscreened,
                                    "excluded_by_first_failing_clause": counts,
                                    "passed_metadata_clauses": screened_passed_meta,
                                    "qualifying": len(qualifying)},
               "qualifying_estimate_in_frame": None if rate is None else {
                   "estimate": rate * passed_meta, "low": lo * passed_meta, "high": hi * passed_meta,
                   "method": "share qualifying among screened repositories that passed c1 to c3 (Wilson 95%), "
                             "times the frame's repositories that passed c1 to c3"},
               "qualifying": len(qualifying)}
    tmp = os.path.join(out, "qualifying.json.tmp")
    json.dump(sorted(qualifying, key=lambda q: q["repo_id"]), open(tmp, "w", encoding="utf-8"), indent=0)
    os.replace(tmp, os.path.join(out, "qualifying.json"))
    tmp = os.path.join(out, "exclusions.json.tmp")
    json.dump(summary, open(tmp, "w", encoding="utf-8"), indent=1)
    os.replace(tmp, os.path.join(out, "exclusions.json"))
    print(json.dumps(summary))


def main():
    enum_dir, out, stage = sys.argv[1], sys.argv[2], sys.argv[3]
    budget = float(sys.argv[sys.argv.index("--budget") + 1]) if "--budget" in sys.argv else 540
    companies = []
    if "--companies" in sys.argv:
        with open(sys.argv[sys.argv.index("--companies") + 1], encoding="utf-8") as f:
            companies = sorted({norm(r.get("company")) for r in csv.DictReader(f)} - {""})
    if "--maker-orgs" in sys.argv:
        with open(sys.argv[sys.argv.index("--maker-orgs") + 1], encoding="utf-8") as f:
            MAKER_ORGS.update(json.load(f)["maker_orgs"])
    global SHARD, SUBSET_ONLY
    SUBSET_ONLY = "--subset-only" in sys.argv
    if "--shard" in sys.argv:
        k, n = sys.argv[sys.argv.index("--shard") + 1].split("/")
        SHARD = (int(k), int(n))
    os.makedirs(out, exist_ok=True)
    repos = load_candidates(enum_dir)
    if stage == "decide":
        return decide(repos, out, companies)
    tok = token()
    {"meta": stage_meta, "tree": stage_tree, "rtree": stage_rtree, "contrib": stage_contrib}[stage](repos, out, tok, budget, companies)


if __name__ == "__main__":
    main()
