import argparse
import csv
import os
from collections import defaultdict


def parse_arguments():
    parser = argparse.ArgumentParser(
        description="Aggregate metagenomic target-level taxonomy read counts across multiple CSV files into a single matrix."
    )
    parser.add_argument(
        "-i",
        "--input-dir",
        required=True,
        help="Path to the directory containing input CSV files.",
    )
    parser.add_argument(
        "-o",
        "--output",
        required=True,
        help="Path for the output aggregated CSV file.",
    )
    return parser.parse_args()


def sort_key(val):
    """Sort numeric tax IDs numerically first, followed by string IDs alphabetically."""
    val_str = str(val).strip()
    if val_str.isdigit():
        return (0, int(val_str))
    return (1, val_str)


def process_csv_files(input_dir, output_file):
    # Data structure: {taxid: {sample_id: read_count}}
    matrix = defaultdict(dict)
    sample_ids = set()

    # Find all CSV files in the folder
    csv_files = [
        os.path.join(input_dir, f)
        for f in os.listdir(input_dir)
        if f.lower().endswith(".csv")
    ]

    if not csv_files:
        print(f"Error: No CSV files found in '{input_dir}'")
        return

    print(f"Processing {len(csv_files)} CSV file(s)...")

    for file_path in csv_files:
        with open(file_path, mode="r", newline="", encoding="utf-8") as infile:
            reader = csv.DictReader(infile)

            for row in reader:
                tax_id = row["taxid_at_target_level"].strip()
                sample_id = row["sample_id"].strip()
                try:
                    read_count = int(float(row["read_count"].strip()))
                except ValueError:
                    read_count = 0

                matrix[tax_id][sample_id] = read_count
                sample_ids.add(sample_id)

    # Sort sample IDs naturally for column headers
    sorted_samples = sorted(list(sample_ids))
    headers = ["FeatureID"] + sorted_samples

    # Write the reshaped feature matrix to output
    with open(output_file, mode="w", newline="", encoding="utf-8") as outfile:
        writer = csv.writer(outfile)
        writer.writerow(headers)

        # Sort tax IDs safely even with mixed numeric and string values
        for tax_id in sorted(matrix.keys(), key=sort_key):
            row = [tax_id]
            for sample in sorted_samples:
                # Default to 0 read counts if the taxid was not found in a specific sample file
                row.append(matrix[tax_id].get(sample, 0))
            writer.writerow(row)

    print(f"Successfully generated matrix file: '{output_file}'")


def main():
    args = parse_arguments()
    process_csv_files(args.input_dir, args.output)


if __name__ == "__main__":
    main()
