"""
Build a HALF graph (train/test split) from an already-built full genome-wide graph
(1_build_graph.py output) plus a published per-half edges file.

The split is BY INDIVIDUAL only: both halves reuse the identical nodes/clusters of the full
graph (same node indexing), so embeddings and clusters line up node-for-node across halves.
Only the carrier columns (which individuals) and the edges (co-occurrence recomputed within the
half, shipped with a final `lift` column) differ.

INPUT
  --full-dir    a 1_build_graph.py output dir with nodes.csv.gz, carriers.npz, individuals.txt
                (default haplograph/genome)
  --individuals a text file, one individual ID per line = the half's members (e.g. half_A.txt).
                IDs must match individuals.txt in --full-dir.
  --edges-file  the half's edges CSV with header `source,target,weight,lift` (already thresholded,
                e.g. l5w5). `lift` is trusted as-is; edge weight in the graph = log1p(lift).

OUTPUT (in --out, default haplograph/<name-from-individuals-file>)
  nodes.csv.gz     same rows as --full-dir, but `support` recomputed on the half's carriers
  individuals.txt  the half's individuals, in --full-dir order (subset)
  carriers.npz     CSR uint8 [N, I_half], carriers restricted to the half's individuals
  graph.npz        CSR float32 [N, N], symmetric, log1p(lift) from --edges-file
  graph_info.json  counts + provenance

NOTE  Nodes are NOT dropped when their half-support is 0, so halfA and halfB keep identical
      node indexing (required for train-on-A / test-on-B comparison). Those nodes are simply
      isolated / zero-support in that half.

USAGE
  python 1b_build_split.py --individuals splits/half_A.txt --edges-file halfA_edges.csv --out haplograph/halfA
  python 1b_build_split.py --individuals splits/half_B.txt --edges-file halfB_edges.csv --out haplograph/halfB

REQUIRES  numpy, pandas, scipy
"""
import argparse
import json
import os
import time

import numpy as np
import pandas as pd
import scipy.sparse as sp


def log(msg=""):
    print(msg, flush=True)


def build(args):
    t0 = time.time()
    full = args.full_dir

    # ---- nodes (shared with the full graph) ---------------------------------
    nodes = pd.read_csv(os.path.join(full, "nodes.csv.gz"))
    n = len(nodes)
    id_to_node = dict(zip(nodes["id"].to_numpy(), nodes["node"].to_numpy()))
    log(f"[split] {n:,} nodes from {full}")

    # ---- individuals: map the half's IDs to full-graph column positions ------
    full_inds = [l.strip() for l in open(os.path.join(full, "individuals.txt")) if l.strip()]
    pos = {s: j for j, s in enumerate(full_inds)}
    half = [l.strip() for l in open(args.individuals) if l.strip()]
    missing = [s for s in half if s not in pos]
    if missing:
        raise SystemExit(f"{len(missing)} individuals from {args.individuals} are not in "
                         f"{full}/individuals.txt, e.g. {missing[:5]}")
    cols = np.array([pos[s] for s in half], dtype=np.int64)
    log(f"  {len(half):,} half individuals (of {len(full_inds):,} in the full graph)")

    # ---- carriers: subset columns to the half, recompute support -------------
    C_full = sp.load_npz(os.path.join(full, "carriers.npz")).tocsr()
    if C_full.shape[0] != n:
        raise SystemExit(f"carriers.npz has {C_full.shape[0]} rows, nodes.csv.gz has {n}")
    carriers = C_full[:, cols].tocsr().astype(np.uint8)
    carriers.sort_indices()
    support = np.asarray(carriers.sum(axis=1)).ravel().astype(np.int64)
    log(f"  carriers subset to [{carriers.shape[0]:,} x {carriers.shape[1]:,}]; "
        f"{int((support == 0).sum()):,} nodes have 0 carriers in this half")

    # ---- edges: stream the half's CSV, map ids -> node idx, weight = log1p(lift)
    S, T, W = [], [], []
    n_rows = n_unknown = 0
    usecols = ["source", "target", "lift"]
    for chunk in pd.read_csv(args.edges_file, usecols=usecols,
                             dtype={"source": str, "target": str, "lift": np.float64},
                             chunksize=args.chunksize):
        s = chunk["source"].map(id_to_node).to_numpy()
        t = chunk["target"].map(id_to_node).to_numpy()
        lift = chunk["lift"].to_numpy()
        n_rows += len(chunk)
        bad = pd.isna(s) | pd.isna(t)
        n_unknown += int(bad.sum())
        ok = ~bad & (s != t) if len(chunk) else np.array([], bool)
        s = s[ok].astype(np.int64); t = t[ok].astype(np.int64); lift = lift[ok]
        S.append(s); T.append(t); W.append(np.log1p(lift).astype(np.float32))
        if n_rows % (args.chunksize * 10) == 0:
            log(f"    read {n_rows:,} edge rows...")
    S = np.concatenate(S) if S else np.empty(0, np.int64)
    T = np.concatenate(T) if T else np.empty(0, np.int64)
    W = np.concatenate(W) if W else np.empty(0, np.float32)
    log(f"  edges: {len(S):,} kept of {n_rows:,} rows"
        + (f", {n_unknown:,} with ids not in the node set" if n_unknown else ""))

    A = sp.coo_matrix((W, (S, T)), shape=(n, n)).tocsr()
    A.sum_duplicates()
    A = A.maximum(A.T).tocsr()                 # co-occurrence is symmetric
    A.setdiag(0); A.eliminate_zeros(); A.sort_indices()

    # ---- write --------------------------------------------------------------
    os.makedirs(args.out, exist_ok=True)
    out_nodes = nodes.copy()
    out_nodes["support"] = support             # half-support replaces full-support
    out_nodes.to_csv(os.path.join(args.out, "nodes.csv.gz"), index=False)
    with open(os.path.join(args.out, "individuals.txt"), "w") as f:
        f.write("\n".join(half))
    sp.save_npz(os.path.join(args.out, "carriers.npz"), carriers)
    sp.save_npz(os.path.join(args.out, "graph.npz"), A)
    deg = np.diff(A.indptr)
    info = {
        "source": "1b_build_split.py", "full_dir": full,
        "individuals_file": args.individuals, "edges_file": args.edges_file,
        "edge_value": "log1p(lift)", "lift": "trusted from edges_file (not recomputed)",
        "n_nodes": int(n), "n_edges": int(A.nnz // 2), "n_individuals": len(half),
        "zero_support_nodes": int((support == 0).sum()),
        "isolated_nodes": int((deg == 0).sum()),
    }
    with open(os.path.join(args.out, "graph_info.json"), "w") as f:
        json.dump(info, f, indent=2)
    log(f"  graph: {n:,} nodes, {A.nnz // 2:,} edges, {len(half):,} individuals, "
        f"isolated {int((deg == 0).sum()):,}  ({time.time() - t0:.0f}s)")
    log(f"  wrote {args.out}/  -> run 2_ancestry_labels.py --graph-dir {args.out}")


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--full-dir", default="haplograph/genome",
                    help="1_build_graph.py output with nodes.csv.gz, carriers.npz, individuals.txt")
    ap.add_argument("--individuals", required=True, help="half member IDs, one per line (e.g. half_A.txt)")
    ap.add_argument("--edges-file", required=True,
                    help="half edges CSV: header source,target,weight,lift (lift trusted as-is)")
    ap.add_argument("--out", help="output dir (default haplograph/<individuals filename stem>)")
    ap.add_argument("--chunksize", type=int, default=2_000_000, help="edge rows read at a time")
    args = ap.parse_args()
    if not args.out:
        stem = os.path.splitext(os.path.basename(args.individuals))[0]
        args.out = os.path.join("haplograph", stem)
    build(args)
    log("done.")


if __name__ == "__main__":
    main()
