
# generate_pheno_plink_fast.py  (explicit DO/NON-DO via panel_type)
from __future__ import annotations
import os
import io
import math
import logging
from typing import Dict, List, Union

import numpy as np
import pandas as pd

from plinkformatter.plink_utils import (
    generate_bed_bim_fam,
    calculate_kinship_from_pedmap,
    rewrite_pheno_ids_from_fam,
)
from plinkformatter.generate_pheno_plink import extract_pheno_measure


def _norm_id(x) -> str:
    """
    Normalize IDs used to join DO PED V1 with pheno['animal_id'].

    - Strip whitespace.
    - If numeric, collapse "123", "123.0", "123.000" → "123".
    - Leave non-numeric IDs (e.g. "DO-123") untouched apart from stripping.
    """
    s = str(x).strip()
    if s == "":
        return s

    # Try to canonicalize numeric IDs first
    try:
        f = float(s)
        if f.is_integer():
            return str(int(f))
        # Non-integer numeric IDs: avoid scientific notation
        return ("%.10g" % f).rstrip()
    except Exception:
        # Not numeric: fall back to simple cleanup
        if s.endswith(".0"):
            s = s[:-2]
        return s


# ----------------------------- NON-DO PATH ----------------------------- #
def generate_pheno_plink_fast_non_do(
    ped_file: str,
    map_file: str,
    pheno: pd.DataFrame,
    outdir: str,
) -> pd.DataFrame:
    """
    NON-DO behavior (matches Hao; this is your validated path):
      - replicate-level rows, keyed by STRAIN
      - FID = IID = STRAIN
      - PID/MID = 0; SEX=2 if 'f' else 1; PHE=zscore or -9
      - PHENO: 'FID IID zscore value'
      - MAP: '.' rsids -> 'chr_bp'
    """
    os.makedirs(outdir, exist_ok=True)
    if pheno is None or pheno.empty:
        return pd.DataFrame()

    need = ("strain", "sex", "measnum", "value")
    missing = [c for c in need if c not in pheno.columns]
    if missing:
        raise ValueError(f"pheno missing required columns: {missing} (need {list(need)})")

    ph = pheno.copy()
    ph["strain"] = ph["strain"].astype(str).str.replace(" ", "", regex=False)
    ph = ph[ph["sex"].isin(["f", "m"])].copy()
    if ph.empty:
        return ph

    # MAP sanitize
    map_df = pd.read_csv(map_file, header=None, sep=r"\s+", engine="python")
    map_df[1] = np.where(
        map_df[1].astype(str) == ".",
        map_df[0].astype(str) + "_" + map_df[3].astype(str),
        map_df[1].astype(str),
    )

    # Ensure zscore column
    if "zscore" not in ph.columns:
        logging.info("[NON-DO] 'zscore' missing; filling NaN (becomes -9).")
        ph["zscore"] = np.nan

    # Build strain -> byte offset index from reference PED
    ped_offsets: Dict[str, int] = {}
    with open(ped_file, "rb") as f:
        while True:
            pos = f.tell()
            line = f.readline()
            if not line:
                break
            first_tab = line.find(b"\t")
            fid_bytes = (line.strip().split()[0] if first_tab <= 0 else line[:first_tab])
            name = fid_bytes.decode(errors="replace").replace("?", "").replace(" ", "")
            if name and name not in ped_offsets:
                ped_offsets[name] = pos

    ped_strains = set(ped_offsets.keys())
    ph = ph[ph["strain"].isin(ped_strains)].reset_index(drop=True)
    if ph.empty:
        return ph

    # Conservative de-duplication (kept from the working version)
    dedup_keys = [c for c in ["strain", "sex", "measnum", "animal_id"] if c in ph.columns]
    if dedup_keys:
        ph = ph.drop_duplicates(subset=dedup_keys, keep="first")
    else:
        sig_cols = [c for c in ["strain", "sex", "measnum", "zscore", "value"] if c in ph.columns]
        ph = ph.drop_duplicates(subset=sig_cols, keep="first")

    for (measnum, sex), df in ph.groupby(["measnum", "sex"], sort=False):
        measnum = int(measnum)
        sex = str(sex)

        # MAP
        map_out = os.path.join(outdir, f"{measnum}.{sex}.map")
        map_df.to_csv(map_out, sep="\t", index=False, header=False)

        ped_out = os.path.join(outdir, f"{measnum}.{sex}.ped")
        phe_out = os.path.join(outdir, f"{measnum}.{sex}.pheno")

        df = df.sort_values(["strain"], kind="stable").reset_index(drop=True)

        with open(ped_out, "w", encoding="utf-8") as f_ped, open(phe_out, "w", encoding="utf-8") as f_ph:
            for strain, sdf in df.groupby("strain", sort=False):
                with open(ped_file, "rb") as fp:
                    fp.seek(ped_offsets[strain])
                    raw = fp.readline().decode(errors="replace").rstrip("\n")

                parts = raw.split("\t")
                if len(parts) <= 6:
                    parts = raw.split()
                if len(parts) < 7:
                    raise ValueError("Malformed PED: need >=7 columns (6 meta + genotypes)")

                parts[0] = parts[0].replace("?", "").replace(" ", "")
                parts[1] = parts[1].replace("?", "").replace(" ", "")

                for _, r in sdf.iterrows():
                    z = r.get("zscore", np.nan)
                    v = r.get("value", np.nan)
                    try:
                        z = float(z)
                    except Exception:
                        z = np.nan
                    try:
                        v = float(v)
                    except Exception:
                        v = np.nan

                    meta = parts[:6]
                    meta[0] = strain
                    meta[1] = strain
                    meta[2] = "0"
                    meta[3] = "0"
                    meta[4] = "2" if sex == "f" else "1"
                    meta[5] = f"{z}" if math.isfinite(z) else "-9"

                    out = io.StringIO()
                    out.write(" ".join(meta))
                    for gp in parts[6:]:
                        a_b = gp.split(" ")
                        if len(a_b) != 2:
                            a_b = gp.split()
                            if len(a_b) != 2:
                                raise ValueError(f"Genotype pair not splitable into two alleles: {gp!r}")
                        out.write(f" {a_b[0]} {a_b[1]}")
                    f_ped.write(out.getvalue() + "\n")

                    f_ph.write(
                        f"{strain} {strain} "
                        f"{(z if math.isfinite(z) else -9)} "
                        f"{(v if math.isfinite(v) else -9)}\n"
                    )

        logging.info(f"[generate_pheno_plink_fast:NON-DO] wrote {ped_out}, {map_out}, {phe_out}")

    return ph


# ------------------------------- DO PATH ------------------------------- #
def generate_pheno_plink_fast_do(
    ped_file: str,
    map_file: str,
    pheno: pd.DataFrame,
    outdir: str,
) -> pd.DataFrame:
    """
    DO behavior (mirror Hao's 'J:DO' branch):

      - Find animals where pheno.animal_id overlaps PED V1 (after ID normalization).
      - Build a pheno.ped table by aligning pheno rows to PED rows in PED order.
      - For each measnum, write sex-specific PED/MAP/PHENO:
          * PED: V1..last_col of the (updated) PED rows
          * MAP: full map with '.' → 'chr_bp' rsIDs
          * PHENO: FID=V1, IID=V2, zscore, value
    """
    os.makedirs(outdir, exist_ok=True)
    if pheno is None or pheno.empty:
        return pd.DataFrame()

    # Required columns
    need = ("strain", "sex", "measnum", "value", "animal_id")
    missing = [c for c in need if c not in pheno.columns]
    if missing:
        raise ValueError(f"[DO] pheno missing required columns: {missing} (need {list(need)})")

    ph = pheno.copy()
    ph["strain"] = ph["strain"].astype(str).str.replace(" ", "", regex=False)
    ph = ph[ph["sex"].isin(["f", "m"])].copy()
    if ph.empty:
        return ph

    # Hao's DO branch triggers only when strain == "J:DO"
    # If somehow we get here with no J:DO, fall back to NON-DO logic.
    if "J:DO" not in set(ph["strain"]):
        logging.warning("[DO] No 'J:DO' strain in pheno; falling back to NON-DO behavior.")
        return generate_pheno_plink_fast_non_do(ped_file, map_file, pheno, outdir)

    # MAP sanitize (same as NON-DO)
    map_df = pd.read_csv(map_file, header=None, sep=r"\s+", engine="python")
    map_df[1] = np.where(
        map_df[1].astype(str) == ".",
        map_df[0].astype(str) + "_" + map_df[3].astype(str),
        map_df[1].astype(str),
    )

    # Ensure zscore column exists
    if "zscore" not in ph.columns:
        logging.info("[DO] 'zscore' missing; filling NaN (becomes -9).")
        ph["zscore"] = np.nan

    # --- Read full PED (Hao: ped <- fread(ped.file)) ---
    ped = pd.read_csv(ped_file, sep=r"\s+", header=None, engine="python")
    ncols = ped.shape[1]
    ped.columns = [f"V{i+1}" for i in range(ncols)]

    # Normalize IDs like Hao's as.numeric() matching behavior:
    #   collapse "123", "123.0", "123.000" → "123"
    ped["id_norm"] = ped["V1"].map(_norm_id)
    ph["animal_id_norm"] = ph["animal_id"].map(_norm_id)

    # Compute overlapping IDs in PED order (Hao: overlap.id = intersect(pheno$animal_id, ped$V1))
    # We preserve PED order by iterating ped["id_norm"].
    ph_ids = set(ph["animal_id_norm"])
    overlap_ids = [aid for aid in ped["id_norm"] if aid in ph_ids]

    if not overlap_ids:
        logging.info("[DO] No overlap between pheno animal_id and PED V1; nothing to do.")
        # return empty but keep schema
        return ph.iloc[0:0].copy()

    # ped.overlap.id = ped %>% filter(V1 %in% overlap.id)
    ped_overlap = ped[ped["id_norm"].isin(overlap_ids)].copy().reset_index(drop=True)

    # pheno.overlap.id = pheno %>% filter(animal_id %in% overlap.id) %>%
    #                     mutate(animal_id = as.numeric(animal_id)) %>%
    #                     slice(match(ped.overlap.id$V1, animal_id))
    ph_overlap = ph[ph["animal_id_norm"].isin(overlap_ids)].copy()

    # Emulate slice(match(...)): for each PED id_norm, pick the *first* pheno row with that id
    first_idx: Dict[str, int] = {}
    for idx, aid in ph_overlap["animal_id_norm"].items():
        if aid not in first_idx:
            first_idx[aid] = idx

    try:
        ordered_idx = [first_idx[aid] for aid in ped_overlap["id_norm"]]
    except KeyError as e:
        missing_id = str(e)
        raise ValueError(f"[DO] PED id {missing_id!r} not found in pheno after normalization") from None

    ph_ordered = ph_overlap.loc[ordered_idx].reset_index(drop=True)

    # Sanity check (Hao: stopifnot(all.equal(...)))
    if not np.array_equal(ped_overlap["id_norm"].values, ph_ordered["animal_id_norm"].values):
        raise ValueError(
            "[DO] PED vs pheno ID order mismatch after alignment: "
            "ped_overlap.id_norm vs pheno.animal_id_norm differ."
        )

    # pheno.ped = ped.overlap.id with extra columns (sex, measnum, zscore, value)
    pheno_ped = ped_overlap.copy()
    pheno_ped["sex"] = ph_ordered["sex"].values
    pheno_ped["measnum"] = ph_ordered["measnum"].values
    pheno_ped["zscore"] = ph_ordered["zscore"].values
    pheno_ped["value"] = ph_ordered["value"].values

    # V5 = sex (2 for f, 1 for m); V6 = zscore (Hao: use zscore as phenotype column)
    pheno_ped["V5"] = np.where(
        pheno_ped["sex"] == "f",
        2,
        np.where(pheno_ped["sex"] == "m", 1, pheno_ped["V5"]),
    )
    # zscore → V6, NaN → -9 so PLINK has a valid phenotype code
    z_as_float = pd.to_numeric(pheno_ped["zscore"], errors="coerce")
    pheno_ped["V6"] = z_as_float.where(np.isfinite(z_as_float), -9.0)

    # Column subset for PED: V1:last_col(), exactly like Hao
    v_cols = [c for c in pheno_ped.columns if c.startswith("V")]

    # For each measnum, write sex-separated PED/MAP/PHENO
    for meas in sorted(pheno_ped["measnum"].unique()):
        df_meas = pheno_ped[pheno_ped["measnum"] == meas]

        # female
        for sex in ("f", "m"):
            df_sex = df_meas[df_meas["sex"] == sex]
            if df_sex.empty:
                continue

            meas_int = int(meas)
            map_out = os.path.join(outdir, f"{meas_int}.{sex}.map")
            ped_out = os.path.join(outdir, f"{meas_int}.{sex}.ped")
            phe_out = os.path.join(outdir, f"{meas_int}.{sex}.pheno")

            # PED: V1:last_col()
            df_sex[v_cols].to_csv(ped_out, sep=" ", header=False, index=False)

            # MAP: same for both sexes
            map_df.to_csv(map_out, sep="\t", header=False, index=False)

            # PHENO: FID = V1, IID = V2, zscore, value
            phe_df = pd.DataFrame(
                {
                    "FID": df_sex["V1"].astype(str),
                    "IID": df_sex["V2"].astype(str),
                    "zscore": df_sex["zscore"],
                    "value": df_sex["value"],
                }
            )
            phe_df.to_csv(phe_out, sep=" ", header=False, index=False)

            logging.info(f"[generate_pheno_plink_fast:DO] wrote {ped_out}, {map_out}, {phe_out}")

    return ph


# ------------------------------- WRAPPER ------------------------------- #
def generate_pheno_plink_fast(
    ped_file: str,
    map_file: str,
    pheno: pd.DataFrame,
    outdir: str,
    ncore: int = 1,
    *,
    panel_type: str = "NON_DO",   # <-- explicit control
) -> pd.DataFrame:
    """
    Wrapper that dispatches to DO or NON-DO implementation based on explicit panel_type.
      panel_type ∈ {"DO","NON_DO"}  (default NON_DO to preserve current behavior)
    """
    if pheno is None or pheno.empty:
        os.makedirs(outdir, exist_ok=True)
        return pd.DataFrame()

    pt = (panel_type or "NON_DO").upper()
    if pt == "DO":
        logging.info("[generate_pheno_plink_fast] using DO panel_type")
        return generate_pheno_plink_fast_do(ped_file, map_file, pheno, outdir)
    elif pt == "NON_DO":
        logging.info("[generate_pheno_plink_fast] using NON-DO panel_type")
        return generate_pheno_plink_fast_non_do(ped_file, map_file, pheno, outdir)
    else:
        raise ValueError(f"panel_type must be 'DO' or 'NON_DO', got {panel_type!r}")


# ----------------------------- Orchestrator ---------------------------- #
def fast_prepare_pylmm_inputs(
    ped_file: str,
    map_file: str,
    measure_id_directory: str,
    measure_ids: List,
    outdir: str,
    ncore: int,
    plink2_path: str,
    *,
    panel_type: str = "NON_DO",
    ped_pheno_field: str = "zscore",
    maf_threshold: Union[float, None] = None,
) -> None:
    """
    Orchestrate extraction and PLINK file generation (public API + panel_type):

      1) Extract phenotype rows for requested measure_ids.
      2) generate_pheno_plink_fast(..., panel_type=...) -> writes <meas>.<sex>.ped/.map/.pheno
      3) PLINK2 from --pedmap -> BED/BIM/FAM   (geno 0.1, mind 0.1)
      4) Rewrite PHENO IIDs from .fam (exact FID/IID order + suffixes)
      5) Kinship from --pedmap (square .rel)
    """
    os.makedirs(outdir, exist_ok=True)

    pheno = extract_pheno_measure(measure_id_directory, measure_ids)
    if pheno is None or pheno.empty:
        logging.info("[fast_prepare_pylmm_inputs] no phenotype rows extracted; nothing to do.")
        return

    used = generate_pheno_plink_fast(
        ped_file=ped_file,
        map_file=map_file,
        pheno=pheno,
        outdir=outdir,
        ncore=ncore,
        panel_type=panel_type,
    )
    if used is None or used.empty:
        logging.info("[fast_prepare_pylmm_inputs] no usable phenotypes after PED/MAP intersection; nothing to do.")
        return

    for measure_id in measure_ids:
        base_id = str(measure_id).split("_", 1)[0]
        for sex in ("f", "m"):
            ped_path   = os.path.join(outdir, f"{base_id}.{sex}.ped")
            map_path   = os.path.join(outdir, f"{base_id}.{sex}.map")
            out_prefix = os.path.join(outdir, f"{base_id}.{sex}")

            if not (os.path.exists(ped_path) and os.path.exists(map_path)):
                continue

            logging.info(f"[fast_prepare_pylmm_inputs] make BED/BIM/FAM for {base_id}.{sex}")
            generate_bed_bim_fam(
                plink2_path=plink2_path,
                ped_file=ped_path,
                map_file=map_path,
                output_prefix=out_prefix,
                relax_mind_threshold=False,
                maf_threshold=maf_threshold,
                sample_keep_path=None,
                autosomes_only=False,
            )

            # Align PHENO IIDs to FAM IIDs (strict 1:1; no dedup)
            fam_path   = f"{out_prefix}.fam"
            pheno_path = os.path.join(outdir, f"{base_id}.{sex}.pheno")
            rewrite_pheno_ids_from_fam(pheno_path, fam_path, pheno_path)

            logging.info(f"[fast_prepare_pylmm_inputs] compute kinship for {base_id}.{sex} (from --pedmap)")
            calculate_kinship_from_pedmap(
                plink2_path=plink2_path,
                pedmap_prefix=out_prefix,
                kin_prefix=os.path.join(outdir, f"{base_id}.{sex}.kin"),
            )


