#!/usr/bin/env python3
from pathlib import Path
import argparse
import pandas as pd


def first_present(cols, candidates):
    cmap = {c.lower(): c for c in cols}
    for c in candidates:
        if c.lower() in cmap:
            return cmap[c.lower()]
    return None


def main():
    ap = argparse.ArgumentParser()
    ap.add_argument("--input", required=True, help="Source CSV with run01 font-tracking rows")
    ap.add_argument("--output", default="reports/10_font_tracking/10r1_edges.csv")
    ap.add_argument("--left_col", default=None)
    ap.add_argument("--right_col", default=None)
    ap.add_argument("--weight_col", default=None)
    ap.add_argument("--min_weight", type=float, default=1.0)
    args = ap.parse_args()

    src = Path(args.input)
    out = Path(args.output)
    out.parent.mkdir(parents=True, exist_ok=True)

    df = pd.read_csv(src)

    left = args.left_col or first_present(df.columns, [
        "cluster", "cluster_id", "case_id", "defendant", "person", "name",
        "left", "source", "src", "node_a"
    ])
    right = args.right_col or first_present(df.columns, [
        "font_hash", "font_id", "font", "object_hash", "right", "target", "dst", "node_b"
    ])
    weight = args.weight_col or first_present(df.columns, [
        "weight", "doc_count", "docs", "count", "n", "value"
    ])

    if left is None or right is None:
        raise SystemExit(
            f"Could not auto-detect left/right columns.\n"
            f"Columns present:\n- " + "\n- ".join(df.columns)
        )

    if weight is None:
        df["__weight__"] = 1
        weight = "__weight__"

    e = df[[left, right, weight]].copy()
    e.columns = ["left", "right", "weight"]
    e["left"] = e["left"].astype(str).str.strip()
    e["right"] = e["right"].astype(str).str.strip()
    e["weight"] = pd.to_numeric(e["weight"], errors="coerce").fillna(1.0)

    e = e[(e["left"] != "") & (e["right"] != "")]
    e = e[e["weight"] >= args.min_weight]
    e = e.groupby(["left", "right"], as_index=False)["weight"].sum()
    e = e.sort_values("weight", ascending=False)

    e.to_csv(out, index=False)
    print(f"[ok] wrote {out}")
    print(f"[info] rows={len(e):,} unique_left={e['left'].nunique():,} unique_right={e['right'].nunique():,}")
    print(f"[info] using columns: left={left}, right={right}, weight={weight}")


if __name__ == "__main__":
    main()
