import pytest
import tempfile
import os
import pandas as pd
from pathlib import Path
from talenWF import FindTALTask



class TestFindTALTask:
    """Test the FindTALTask class."""
    
    @pytest.fixture
    def sample_fasta_file(self):
        """Create a temporary FASTA file for testing with different sequences."""
        seq_name = "test_seq"
        # sequence = "C" + "CT" + "C"*26 + "T" + "C"*26 + "AA" + "C"
        sequence = "C" + "TC" + "C"*26 + "T" + "C"*26 + "CA"
        with tempfile.NamedTemporaryFile(mode='w', suffix='.fasta', delete=False) as f:
            f.write(f">{seq_name}\n")
            f.write(sequence + "\n")
            temp_file = f.name
        yield temp_file
        os.unlink(temp_file)
    
    @pytest.fixture
    def output_file(self):
        """Create a temporary output file path."""
        with tempfile.NamedTemporaryFile(suffix='.txt', delete=False) as f:
            temp_file = f.name
        yield temp_file
        if os.path.exists(temp_file):
            os.unlink(temp_file)
    
    def test_find_tal_task_basic(self, sample_fasta_file, output_file):
        """Test basic functionality of FindTALTask with different sequences."""
        # Create FindTALTask instance
        task = FindTALTask(
            fasta=sample_fasta_file,
            min_spacer=14,
            max_spacer=18,
            array_min=14,
            array_max=18,
            outpath=output_file,
            filter_base=30,
        )

        # Run the task
        task.run()
        
        # Check that output file was created
        assert os.path.exists(output_file)
        
        # Check that output file can be read properly (TSV with 2 rows skipped)
        out = pd.read_csv(output_file, delimiter = '\t')
        assert out.columns[0] == "Sequence Name", "First column should be Sequence Name"

        print(out[['TAL1 start','TAL2 start']].value_counts())

        for i,row in out.iterrows():
            print(dict(row))
        # print(out.columns)
        
        # assert len(out) == 5, "Expected 5 rows"
        # for spac_len in range(14,19):
        #     assert out["Spacer length"].isin([spac_len]).any(), f"Spacer length {spac_len} not found"
        # for i,row in out.iterrows():
        #     print(row["Plus strand sequence"])
        #     assert row["Spacer length"] == len(row["Plus strand sequence"].split()[2])
        
    
    # def test_find_tal_task_without_filter(self, sample_fasta_file, output_file):
    #     """Test FindTALTask without filter_base."""
    #     task = FindTALTask(
    #         fasta=sample_fasta_file,
    #         min_spacer=14,
    #         max_spacer=18,
    #         array_min=14,
    #         array_max=18,
    #         outpath=output_file,
    #     )

        
    #     df = task.run()
        
    #     assert df is not None
    #     assert os.path.exists(output_file)

# TODO: add tests with filter base outside of the sequence
# TODO: add tests with filter base less than min_dist/2
# TODO: add tests with filter base greater than len(seq) - max_dist/2