"""
make_synthetic_height.py -- synthetic polygenic height for 4b

WHY SYNTHETIC: 1000 Genomes has no measured height (IGSR / dataset README).
Any quantitative trait here is simulated. Results test the PIPELINE, not biology
-- label "synthetic height" wherever reported.

ENCODING (--encoding): 4b accepts ONLY 0/1 hash strings. Both modes below are
binary so 4b will accept them.
  bit   one char per causal cluster: carried -> "1", not -> "0".
  run   (DEFAULT) run-length: carried -> "1"*k, not -> "0"*k, where
        k = --bases-per-cluster. Makes the string longer and less sparse
        (sequence-like) while staying binary -- the closest to a DNA-like
        encoding that 4b's 0/1-only validator will accept.

MODEL: height = base + sum(beta_j * carry_ij) + noise; hash encodes the same
carried causal clusters, so the signal is present and nearly linear.
corr(genetic, height) is printed as the achievable ceiling. (Linear baseline on
the raw bits recovers ~that; a null 4b R^2 therefore isolates the input format,
not the signal.)

NOTE: demonstration hash, not the project's 64-bit production format.

USAGE
  python make_synthetic_height.py --graph-dir haplograph/genome \
      --individuals splits/half_A.txt --encoding run --bases-per-cluster 4 --out height_run.tsv
  python 4b_finetune_evo2_hash.py --hash-pheno height_run.tsv \
      --task regression --train-blocks 2 --epochs 8 --lr 1e-6 --head-lr 1e-2

TUNING  --encoding {run,bit}  --bases-per-cluster k (run mode; keep n_causal*k <= ~4000)
        --n-causal  --effect-sd  --noise-sd  --base  --seed
REQUIRES numpy, scipy
"""
import argparse
import numpy as np
import scipy.sparse as sp
import os


def main():
    ap = argparse.ArgumentParser(description=__doc__,
                                 formatter_class=argparse.RawDescriptionHelpFormatter)
    ap.add_argument("--graph-dir", default="haplograph/genome")
    ap.add_argument("--individuals")
    ap.add_argument("--out", required=True)
    ap.add_argument("--encoding", choices=["run", "bit"], default="run")
    ap.add_argument("--bases-per-cluster", type=int, default=4)
    ap.add_argument("--n-causal", type=int, default=256)
    ap.add_argument("--effect-sd", type=float, default=3.0)
    ap.add_argument("--base", type=float, default=170.0)
    ap.add_argument("--noise-sd", type=float, default=4.0)
    ap.add_argument("--seed", type=int, default=0)
    args = ap.parse_args()

    rng = np.random.default_rng(args.seed)

    inds = [l.strip() for l in open(os.path.join(args.graph_dir, "individuals.txt")) if l.strip()]
    C = sp.load_npz(os.path.join(args.graph_dir, "carriers.npz")).tocsc()
    n_clusters, n_ind = C.shape
    assert n_ind == len(inds), f"carriers has {n_ind} individuals, individuals.txt has {len(inds)}"

    if args.individuals:
        keep = set(l.strip() for l in open(args.individuals) if l.strip())
        cols = [j for j, s in enumerate(inds) if s in keep]
        if not cols:
            raise SystemExit("no overlap between --individuals and individuals.txt")
        sel_inds = [inds[j] for j in cols]
    else:
        cols = list(range(n_ind))
        sel_inds = inds
    cols = np.array(cols)

    sub = C[:, cols].tocsr()
    freq = np.asarray(sub.sum(axis=1)).ravel() / len(cols)
    eligible = np.where((freq > 0.05) & (freq < 0.95))[0]
    if len(eligible) < args.n_causal:
        raise SystemExit(f"only {len(eligible)} clusters polymorphic in this set; lower --n-causal")
    causal = np.sort(rng.choice(eligible, size=args.n_causal, replace=False))

    beta = rng.normal(0, args.effect_sd, size=len(causal))
    carried = np.asarray(sub[causal].todense()).T.astype(np.float64)
    genetic = carried @ beta
    noise = rng.normal(0, args.noise_sd, size=len(sel_inds))
    height = np.clip(args.base + genetic + noise, 140, 210)

    k = args.bases_per_cluster if args.encoding == "run" else 1
    one, zero = "A" * k, "T" * k

    with open(args.out, "w") as f:
        f.write("hash\theight\n")
        for i, s in enumerate(sel_inds):
            h = "".join(one if carried[i, j] else zero for j in range(len(causal)))
            f.write(f"{h}\t{height[i]:.1f}\n")

    r = np.corrcoef(genetic, height)[0, 1]
    print(f"wrote {len(sel_inds):,} rows to {args.out}")
    print(f"  encoding={args.encoding}, {len(causal)} causal clusters, "
          f"string length {len(causal)*k} chars (0/1), noise_sd {args.noise_sd}")
    print(f"  (sanity) corr(genetic component, final height) = {r:.3f}  -- achievable ceiling")
    print("  NOTE: height is SYNTHETIC. 1000G has no measured height.")


if __name__ == "__main__":
    main()
