#!/usr/bin/env python3
import sys
import os
import shutil
import subprocess
import itertools

TEST_SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
BIN_DIR = sys.argv[1] # Provided by ctest call

result = subprocess.run(
    [
        os.path.join(BIN_DIR, "kissplice"),
        "-k", "25", "-M", "1000",
        "-r", os.path.join(TEST_SCRIPT_DIR, "data", "HBM75brain_100000.fasta"),
        "-r", os.path.join(TEST_SCRIPT_DIR, "data", "HBM75liver_100000.fasta"),
        "--keep-counts",
        "-o", os.path.join(TEST_SCRIPT_DIR, "results"),
    ],
    check = True, capture_output = True
)
assert result.stderr == b""

# Extract entries at column_index, sort them and compare to a reference in data/<filename>0 (pre-sorted)
def compare_sorted_entries(filename: str, column_index: int):
    # Extract column and sort entries of result
    with open(os.path.join(TEST_SCRIPT_DIR, "results", filename)) as lines:
        # Extract the column but restore the newline to have useful diffs
        result_entries = [l.strip().split()[column_index] + "\n" for l in lines]
    result_entries.sort()
    with open(os.path.join(TEST_SCRIPT_DIR, "results", filename + "0"), "w") as f:
        f.writelines(result_entries)

    # On Linux these sorted entries are reproducible and exact.
    # On MacOS they are almost the same, with one difference for 10k lines.
    # Until this is investigated further, assume it is ok and add some tolerance to the test
    diff_run = subprocess.run(
        [
            "diff",
            os.path.join(TEST_SCRIPT_DIR, "data", filename + "0"),
            os.path.join(TEST_SCRIPT_DIR, "result", filename + "0"),
        ],
        capture_output = True
    )
    diff_line_count = diff_run.stdout.count(ord("\n"))
    allowed_lines_of_diff = 10
    assert diff_line_count <= allowed_lines_of_diff # On error analyze the dumped files

compare_sorted_entries("graph_HBM75brain_100000_HBM75liver_100000_k25.edges", column_index = 2)
compare_sorted_entries("graph_HBM75brain_100000_HBM75liver_100000_k25.nodes", column_index = 1)
compare_sorted_entries("graph_HBM75brain_100000_HBM75liver_100000_k25.abundance", column_index = 0)
    
shutil.rmtree(os.path.join(TEST_SCRIPT_DIR, "results"))