#!/usr/bin/env -S awk -f
# Extract the FASTA record id with the longest sequence.
# Takes a two columns file with record id, record length
# and the FASTA file.
#
# Usage: filter_longest.awk protein_lengths.tsv proteins.fasta

NR==FNR {
    gsub(">", "", $1)
    protein_length[$1] = $2
    next
}

{
    gene_id = $4
    gsub("gene:", "", gene_id)
    isoform_id = $0
    gsub(">", "", isoform_id)
    if (gene_id in max_length) {
        if (protein_length[isoform_id] > max_length[gene_id]) {
            max_length[gene_id] = protein_length[isoform_id]
            max_length_isoform[gene_id] = isoform_id
        }
    } else {
        max_length[gene_id] = protein_length[isoform_id]
        max_length_isoform[gene_id] = isoform_id
    }
}

END {
    for (gene_id in max_length_isoform) {
        print max_length_isoform[gene_id]
    }
}
