#!usr/bin/perl -w

use strict;
use warnings;
use Getopt::Long;
use FindBin;
use File::Spec;


# perl /media/xiangyang/fa0b5a1c-cdf8-456c-b415-bd931d086eb0/home/xiangyang/Desktop/tool_dev/AMannot/AManno/NCBI-AMR结构化数据库构建步骤/cp_mercury_hgcAB.pl -i /media/xiangyang/fa0b5a1c-cdf8-456c-b415-bd931d086eb0/home/xiangyang/Desktop/tool_dev/AMannot/AManno/NCBI-AMR结构化数据库构建步骤/nucleotide20241116.fna

my %options = (
    'infile'                              => undef,  
    'workplace'                           => undef
);
 
GetOptions(
    'i|infile=s'                          => \$options{infile},    
    'o|workplace=s'                       => \$options{workplace}

);

my $home_directory = $FindBin::Bin;           # obtaining the home directory where MG_Pipeline.pl located

#check for workplace options
my $workplace;
if ( defined( $options{workplace} ) ) {
    $workplace = File::Spec->rel2abs($options{workplace});
    mkdir $workplace;
}else {

    $workplace = "$home_directory/NCBI-AMR-nr-20241116_workplace";
    mkdir $workplace;
}


my $infile = $options{infile}; 
 
my $seq_file = "$workplace/seq_file.fasta";
my $id_list = "$workplace/id_list";


my %hash_classification;
 
# GeneID|antibiotic classes|ARG name|Mechanism


open (SF, ">$seq_file");
open (ID_LIST, ">$id_list");

# >EAT05628.1|mercury|hgcA|microbial Hg methylation gene hgcA
my %seq = parse_fasta($infile);

foreach (keys %seq) {
    chomp;
    my @arr = split /\|/, $_;
    my $header_id = $arr[0];
    $header_id =~ s/\:$//g;
    $header_id =~ s/\:/_/g;
    my $gene = $arr[2];
    my $NCBI_annotation = $arr[3];
    $NCBI_annotation =~ s/ /_/g;
    my $class = $arr[1]; 
    $class =~ s/ /_/g;

    my $final_id = $header_id." ".$NCBI_annotation;

    print SF ">$final_id\n$seq{$_}\n"; 
        
    push @{$hash_classification{$class."__".$gene}}, "\'$header_id\'";
    
}

close SF;

foreach (sort keys %hash_classification){
    print ID_LIST "$_\t", "[",join (", ", @{$hash_classification{$_}}) , "]\n"; 

} 

close ID_LIST;




sub parse_fasta {

    my ($infile) = @_;
    my $term     = $/; # input record separator;
    my %seq_hash = (); # key:seqid, val:seq
    open my $INFILE, $infile or die "could not open infile '$infile' : $! \n"; 
    $/ = ">"; # input record separator;
    while(<$INFILE>) {

        chomp;

        next if($_ eq '');
        my ($id, @sequencelines) = split /\n/;

        foreach my $line (@sequencelines) {
            $seq_hash{$id} .= $line;
        }
    }
    $/ = $term;
    return(%seq_hash);

} # end of parse_fasta

