"""Count endogenous retrovirus (LTR class) bases in GRCh38 and T2T-CHM13 v2.0.

Reproduces the ProteinIQ analysis in content/guides/human-genome-viral-dna.mdx.
For each RepeatMasker annotation, the script keeps class LTR hits on the
primary assembly, merges overlapping intervals so no base is counted twice,
and divides by the assembly's non-N bases.

Inputs (downloaded 2026-10-23; md5 of the files used in brackets):

  hg38 rmsk (UCSC default track; RepeatMasker open-4.0.3, RepBase 20130422)
    https://hgdownload.soe.ucsc.edu/goldenPath/hg38/database/rmsk.txt.gz
    [b2e108b535550ba9e3cf83c77417380f]
  hg38 rmskOutCurrent (UCSC "RepeatMasker Viz" rerun, 2018, HMMER + Dfam)
    https://hgdownload.soe.ucsc.edu/goldenPath/hg38/database/rmskOutCurrent.txt.gz
    [85f2738f7b83995fef2fc3fb9df4de66]
  hs1 = T2T-CHM13 v2.0 (UCSC; RepeatMasker crossmatch, Dfam + RepBase 20181026)
    https://hgdownload.soe.ucsc.edu/goldenPath/hs1/bigZips/hs1.repeatMasker.out.gz
    [5cc807e86912c46af52d3bd35f2b833c]
  T2T-CHM13 v2.0 and GRCh38 (T2T consortium; RepeatMasker open-4.1.2-p1, RMBlast,
  Dfam 3.3 plus T2T-CHM13 entries, per T2T/CHM13/browser/html/rmsk.html)
    https://s3-us-west-2.amazonaws.com/human-pangenomics/T2T/CHM13/assemblies/annotation/chm13v2.0_RepeatMasker_4.1.2p1.2022Apr14.bed
    [a08290b83c8b2b20ff1b5e820bfa90e5]
    https://s3-us-west-2.amazonaws.com/human-pangenomics/T2T/CHM13/assemblies/annotation/hg38/hg39_noalt_norandom_RepeatMasker_4.1.2p1.2022Apr14.bed
    [a7ba79878056e472c5e3147d8ee15905]
  Sequence lengths and N runs are read from the 2bit headers with HTTP range
  requests, so the 0.8 GB genomes are not downloaded:
    https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.2bit
    https://hgdownload.soe.ucsc.edu/goldenPath/hs1/bigZips/hs1.2bit

Primary assembly: hg38 sequences without _alt or _fix in the name (chr1-22,
X, Y, M, *_random and chrUn_*); hs1 chr1-22, X, Y, M. The consortium's
GRCh38 file names chromosomes by GenBank accession (CM000663.2 = chr1 ...
CM000685.2 = chrX, from hg38.chromAlias.txt) and has no chrM or scaffolds, so
the like-for-like pair compares chr1-22 and X only. chrY is left out of that
pair because the T2T-CHM13 v2.0 Y comes from a different person (HG002).

Families follow RepeatMasker's class/family labels. Tentative labels ending
in "?", Gypsy, and LTR hits without a family go to "Other or unclassified
LTR". "hits" counts annotation rows (fragments), not intact elements.

Usage (keep downloads outside the repository):

  python -I count_erv_bases.py --hg38-rmsk rmsk.txt.gz \
      --hg38-rmsk-current rmskOutCurrent.txt.gz \
      --hs1-out hs1.repeatMasker.out.gz \
      --chm13-bed chm13v2.0_RepeatMasker_4.1.2p1.2022Apr14.bed \
      --hg38-t2t-bed hg39_noalt_norandom_RepeatMasker_4.1.2p1.2022Apr14.bed \
      --out erv_counts.csv
"""

import argparse
import csv
import gzip
import struct
import urllib.request
from collections import defaultdict

TWOBIT = {
    "hg38": "https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.2bit",
    "hs1": "https://hgdownload.soe.ucsc.edu/goldenPath/hs1/bigZips/hs1.2bit",
}

AUTOSOMES_X = {f"chr{i}" for i in range(1, 23)} | {"chrX"}
# GenBank accessions used by the T2T consortium's GRCh38 annotation.
GRCH38_ACCESSIONS = {f"CM0006{63 + i}.2": f"chr{i + 1}" for i in range(22)} | {"CM000685.2": "chrX"}

FAMILIES = ("ERV1", "ERVK", "ERVL", "ERVL-MaLR")
# Rows reported in the CSV: single categories, then unions of categories.
GROUPS = {
    "ERV1": {"ERV1"},
    "ERVK": {"ERVK"},
    "ERVL": {"ERVL"},
    "ERVL-MaLR": {"ERVL-MaLR"},
    "Other or unclassified LTR": {"other"},
    "ERV1 + ERVK + ERVL (MaLR excluded)": {"ERV1", "ERVK", "ERVL"},
    "ERV1 + ERVK + ERVL + MaLR": set(FAMILIES),
    "All LTR class": set(FAMILIES) | {"other"},
}


def is_primary(chrom):
    return "_alt" not in chrom and "_fix" not in chrom


def read_range(url, start, length):
    req = urllib.request.Request(url, headers={"Range": f"bytes={start}-{start + length - 1}"})
    with urllib.request.urlopen(req) as resp:
        data = resp.read()
    if len(data) != length:
        raise RuntimeError(f"short read from {url}")
    return data


def twobit_sizes(url):
    """Return {sequence: (length, N bases)} from a remote 2bit file."""
    sig, version, count, _ = struct.unpack("<IIII", read_range(url, 0, 16))
    if sig != 0x1A412743 or version != 0:
        raise RuntimeError("unexpected 2bit header")
    index = read_range(url, 16, count * 300)
    pos, offsets = 0, []
    for _ in range(count):
        n = index[pos]
        name = index[pos + 1 : pos + 1 + n].decode()
        offsets.append((name, struct.unpack("<I", index[pos + 1 + n : pos + 5 + n])[0]))
        pos += 5 + n
    out = {}
    for name, off in offsets:
        if not is_primary(name):
            continue
        size, nblocks = struct.unpack("<II", read_range(url, off, 8))
        n_bases = 0
        if nblocks:
            raw = read_range(url, off + 8, 8 * nblocks)
            n_bases = sum(struct.unpack(f"<{nblocks}I", raw[4 * nblocks :]))
        out[name] = (size, n_bases)
    return out


def category(cls, family):
    if cls.rstrip("?") != "LTR":
        return None
    return family if family in FAMILIES else "other"


def rows_ucsc_table(path):
    """UCSC rmsk-style table: 0-based start, separate class and family."""
    with gzip.open(path, "rt") as fh:
        for line in fh:
            f = line.rstrip("\n").split("\t")
            yield f[5], int(f[6]), int(f[7]), f[11], f[12]


def rows_rm_out(path):
    """RepeatMasker .out: 1-based inclusive coordinates, class/family joined."""
    with gzip.open(path, "rt") as fh:
        for line in fh:
            f = line.split()
            if len(f) < 11 or not f[0].isdigit():
                continue
            cls, _, family = f[10].partition("/")
            yield f[4], int(f[5]) - 1, int(f[6]), cls, family


def rows_t2t_bed(path, aliases=None):
    """T2T consortium BED: chrom, start, end, name, score, strand, class, family."""
    with open(path) as fh:
        for line in fh:
            f = line.rstrip("\n").split("\t")
            chrom = aliases.get(f[0], f[0]) if aliases else f[0]
            yield chrom, int(f[1]), int(f[2]), f[6], f[7]


def merged_length(intervals):
    total, cur_s, cur_e = 0, None, None
    for s, e in sorted(intervals):
        if cur_e is None or s > cur_e:
            if cur_e is not None:
                total += cur_e - cur_s
            cur_s, cur_e = s, e
        elif e > cur_e:
            cur_e = e
    if cur_e is not None:
        total += cur_e - cur_s
    return total


def count(rows, sizes):
    by_cat = defaultdict(lambda: defaultdict(list))
    hits = defaultdict(int)
    for chrom, start, end, cls, family in rows:
        if chrom not in sizes:
            continue
        cat = category(cls, family)
        if cat is None:
            continue
        by_cat[cat][chrom].append((start, end))
        hits[cat] += 1
    result = {}
    for label, cats in GROUPS.items():
        chroms = {c for cat in cats for c in by_cat[cat]}
        bases = sum(
            merged_length([iv for cat in cats for iv in by_cat[cat].get(c, ())]) for c in chroms
        )
        result[label] = (sum(hits[c] for c in cats), bases)
    return result


def main():
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("--hg38-rmsk", required=True)
    ap.add_argument("--hg38-rmsk-current", required=True)
    ap.add_argument("--hs1-out", required=True)
    ap.add_argument("--chm13-bed", required=True)
    ap.add_argument("--hg38-t2t-bed", required=True)
    ap.add_argument("--out", required=True)
    args = ap.parse_args()

    sizes = {asm: twobit_sizes(url) for asm, url in TWOBIT.items()}
    ax = {asm: {c: v for c, v in sz.items() if c in AUTOSOMES_X} for asm, sz in sizes.items()}
    t2t_pipeline = "T2T consortium: RepeatMasker 4.1.2-p1, RMBlast, Dfam 3.3 + T2T entries"
    annotations = [
        ("GRCh38 (hg38)", "UCSC rmsk: RepeatMasker open-4.0.3, RepBase 20130422", sizes["hg38"],
         rows_ucsc_table(args.hg38_rmsk)),
        ("GRCh38 (hg38)", "UCSC rmskOutCurrent: 2018 rerun, HMMER + Dfam", sizes["hg38"],
         rows_ucsc_table(args.hg38_rmsk_current)),
        ("T2T-CHM13 v2.0 (hs1)", "UCSC hs1: RepeatMasker crossmatch, Dfam + RepBase 20181026",
         sizes["hs1"], rows_rm_out(args.hs1_out)),
        ("T2T-CHM13 v2.0 (hs1)", t2t_pipeline, sizes["hs1"], rows_t2t_bed(args.chm13_bed)),
        ("GRCh38 (hg38), chr1-22 + X", t2t_pipeline, ax["hg38"],
         rows_t2t_bed(args.hg38_t2t_bed, GRCH38_ACCESSIONS)),
        ("T2T-CHM13 v2.0 (hs1), chr1-22 + X", t2t_pipeline, ax["hs1"],
         rows_t2t_bed(args.chm13_bed)),
    ]
    with open(args.out, "w", newline="") as fh:
        w = csv.writer(fh, lineterminator="\n")
        w.writerow(["assembly", "annotation", "category", "hits", "merged_bases",
                    "non_n_bases", "percent_of_non_n"])
        for asm, ann, sz, rows in annotations:
            non_n = sum(length - n for length, n in sz.values())
            for label, (hits, bases) in count(rows, sz).items():
                w.writerow([asm, ann, label, hits, bases, non_n, f"{100 * bases / non_n:.3f}"])
            print(asm, ann, "non-N bases:", non_n)


if __name__ == "__main__":
    main()
