use std::{collections::HashMap, path::PathBuf};
use clap::Parser;
use finder::{detect_tag_of_definitions, parse_families, parse_position};

mod finder;

#[derive(Parser)]
#[command(version="0.0.1", about="Find Tandemly Arrayed Genes", long_about="Find Tandemly Arrayed Genes in a genome based on gene position and Tandemly Arrayed Genes definition (i. e. number of spacers)")]
struct Cli {
    #[arg(short='f', long="families", value_name="FAMILIES FILE")]
    families: PathBuf,
    
    #[arg(short='p', long="positions", value_name="POSITIONS FILE")]
    positions: PathBuf,

    #[arg(short='d', long="definitions", value_name="TAGs DEFINITIONS", help="Comma seperated integers for the number of spacers to consider")]
    definitions: String
}

fn main() {
    let cli = Cli::parse();

    let gene_families: HashMap<String, u64> = parse_families(cli.families);

    let mut gene_positions: Vec<(String, String, u64, u64)> = parse_position(cli.positions);

    gene_positions.sort_by(|a, b | crate::finder::compare_gene_position(a, b));

    let definitions: Vec<u64> = cli.definitions.split(",").map(|x| x.parse().unwrap()).collect();

    let tag_numbers = detect_tag_of_definitions(&definitions, &gene_positions, &gene_families);

    // Print header
    print!("gene\tfamily\t");
    for (i, definition) in definitions.iter().enumerate() {
        print!("tag{}", definition);
        if (i + 1) < definitions.len() {
            print!("\t");
        }
    }
    print!("\n");
    
    for (gene, (family, tags)) in tag_numbers {
        print!("{}\t{}\t", gene, family);
        for (i, tag) in tags.iter().enumerate() {
            if let Some(tag) = tag {
                print!("{}", tag);
            } else {
                print!("-");
            }
            if (i + 1) < tags.len() {
                print!("\t");
            }
        }
        print!("\n");
    }
}
