#!/usr/bin/env python3
"""
gen_module_dependencies.py — derive real module-level dependency edges and
"god symbol" (highest fan-in) rankings from a CodeGraph SQLite index.

Usage:
    codegraph init <repo>              # build .codegraph/codegraph.db (run on local disk)
    python gen_module_dependencies.py --db <repo>/.codegraph/codegraph.db \
        --out tool-outputs/codegraph/module_dependencies.json

Groups files under internal/<pkg> or cmd/<pkg> as one module (matches this
repo's Go package layout); adjust module_of() for a different layout.
Regenerate any time after code changes.
"""
import argparse, json, sqlite3
from collections import Counter


def module_of(path):
    parts = path.lstrip("./").split("/")
    if parts[0] in ("internal", "cmd") and len(parts) > 2:
        return "/".join(parts[:2])
    return parts[0] if len(parts) > 1 else "(root)"


def main():
    ap = argparse.ArgumentParser(description=__doc__)
    ap.add_argument("--db", required=True)
    ap.add_argument("--out", required=True)
    ap.add_argument("--lang-suffix", default=".go")
    ap.add_argument("--exclude-tests", action="store_true", default=True)
    args = ap.parse_args()

    con = sqlite3.connect(args.db)
    cur = con.cursor()
    where = "file_path like ?"
    params = [f"%{args.lang_suffix}"]
    cur.execute(f"select id, kind, name, file_path from nodes where {where}", params)
    id_info = {r[0]: {"kind": r[1], "name": r[2], "file": r[3]} for r in cur.fetchall()}

    cur.execute("select source, target, kind from edges")
    mod_edges, call_in = Counter(), Counter()
    for s, t, k in cur.fetchall():
        si, ti = id_info.get(s), id_info.get(t)
        if not si or not ti:
            continue
        if k == "calls":
            call_in[t] += 1
        ms, mt = module_of(si["file"]), module_of(ti["file"])
        if ms != mt:
            mod_edges[(ms, mt)] += 1

    cur.execute(f"select id, kind, name, file_path from nodes where {where} and file_path not like '%_test.go'", params)
    nontest = {r[0]: {"kind": r[1], "name": r[2], "file": r[3]} for r in cur.fetchall()}
    top = sorted(((n, c) for n, c in call_in.items() if n in nontest), key=lambda x: -x[1])[:25]

    out = {
        "module_edges": [
            {"source": a, "target": b, "weight": c}
            for (a, b), c in sorted(mod_edges.items(), key=lambda x: -x[1])
        ],
        "top_called_symbols": [
            {"name": nontest[n]["name"], "file": nontest[n]["file"], "kind": nontest[n]["kind"], "in_calls": c}
            for n, c in top
        ],
    }
    with open(args.out, "w") as f:
        json.dump(out, f, indent=2)
    print(f"wrote {args.out}: {len(out['module_edges'])} module edges, {len(out['top_called_symbols'])} top symbols")


if __name__ == "__main__":
    main()
