
#!/usr/bin/env bash
set -euo pipefail

input_file="${1:-clinvar_20261011.vcf.gz}"
output_file="${2:-clinvar_20261011_chr.vcf.gz}"
header_file="${3:-clinvar_20261011_chr.header.vcf.gz}"
alias_file="${4:-hg38.chromAlias.txt}"

# Check dependencies and input files
for cmd in gzip awk bgzip tabix; do
    command -v "$cmd" >/dev/null || {
        echo "Missing command: $cmd" >&2
        exit 1
    }
done

for file in "$input_file" "$alias_file"; do
    [[ -s "$file" ]] || {
        echo "Missing or empty file: $file" >&2
        exit 1
    }
done

# Temporary files
tmp_dir="$(mktemp -d)"
trap 'rm -rf "$tmp_dir"' EXIT

tmp_vcf="$tmp_dir/output.vcf.gz"
tmp_header="$tmp_dir/header.vcf"

gzip -dc "$input_file" |
awk -v ALIAS="$alias_file" -v HEADER="$tmp_header" '
BEGIN {
    FS = OFS = "\t"

    # Load chromosome aliases (NCBI -> UCSC)
    while ((getline line < ALIAS) > 0) {
        if (line ~ /^#/ || line == "") continue

        n = split(line, fields, "\t")
        ucsc = fields[1]

        for (i = 1; i <= n; i++) {
            if (fields[i] != "")
                alias[fields[i]] = ucsc
        }
    }
    close(ALIAS)
}

# Original ClinVar VCF has no contig declarations
/^##contig=/ {
    print "ERROR: Unexpected ##contig header" > "/dev/stderr"
    failed = 1
    exit 1
}

# Preserve header and save a separate copy
/^#/ {
    print $0 >> HEADER
    print
    next
}

# Convert chromosome names
{
    original = $1

    # Exclude GRCh38 fix patch absent from the UCSC hg38
    # reference (hg38.fa.gz). One record in ClinVar 20261011.
    if (original == "NW_009646201.1") {
        excluded++
        next
    }

    # Require a known UCSC chromosome alias
    if (!(original in alias)) {
        print "ERROR: Unmapped chromosome: " original > "/dev/stderr"
        failed = 1
        exit 1
    }

    # Replace chromosome name; preserve other fields
    pos = index($0, "\t")
    if (pos == 0) {
        print "ERROR: Malformed VCF record" > "/dev/stderr"
        failed = 1
        exit 1
    }

    print alias[original] substr($0, pos)
    kept++
}

END {
    if (!failed) {
        print "Retained variants:", kept + 0 > "/dev/stderr"
        print "Excluded variants:", excluded + 0 > "/dev/stderr"
    }
}
' | bgzip -c > "$tmp_vcf"

# Compress header and index VCF
bgzip -c "$tmp_header" > "$tmp_dir/header.vcf.gz"
tabix -f -p vcf "$tmp_vcf"

# Move completed outputs into place
mv -f "$tmp_vcf" "$output_file"
mv -f "$tmp_vcf.tbi" "$output_file.tbi"
mv -f "$tmp_dir/header.vcf.gz" "$header_file"

echo "Wrote: $output_file"
echo "Wrote: $output_file.tbi"
echo "Wrote: $header_file"
