import os
import csv
from typing import List
from ..utils.file_utils import FileUtils
from ..constant import OCV_COLUMN_NAME, UNWRAP_COLUMN_NAME, UNWRAP_DEFAULT_COLUMN_INDEX

class FeedbackAnalysisUtils:
    @staticmethod
    def ocv_feedback_data_clean_tool(input_files: List[str], working_path: str):
        """
        Clean the OCV user feedback data files provided as input, and output the specified column to new intermediate files.
        Args:
            input_files (List[str]): List of input CSV file paths generated by the previous tool.
        Returns:
            List[str]: List of generated intermediate file paths.
        """
        # Define phrases to filter out
        phrases_to_exclude = [
            "Generic - Praise",
            "[Generic] - Not useful or Spam",
            "Praise for Workspaces",
            "Test data"
        ]

        cleaned_files = []
        for file_path in input_files:
            base_name = os.path.splitext(os.path.basename(file_path))[0]
            output_file = os.path.join(working_path, f"{base_name}_cleaned_intermediate.csv")

            with open(file_path, 'r', encoding='utf-8') as infile, open(output_file, 'w', newline='', encoding='utf-8') as outfile:
                reader = csv.reader(infile)
                writer = csv.writer(outfile)

                # Skip the first row (which is a sentence and not part of the header)
                next(reader, None)

                # Read the header to find the index of "Issue[0].Title"
                header = next(reader, None)
                if not header or OCV_COLUMN_NAME not in header:
                    return f"Error: Column '{OCV_COLUMN_NAME}' not found in file {file_path}"

                issue_title_index = header.index(OCV_COLUMN_NAME)

                # Write the header for the output file
                writer.writerow([OCV_COLUMN_NAME])

                for row in reader:
                    if len(row) > issue_title_index:
                        cleaned_text = FileUtils.replace_stop_words(row[issue_title_index])

                        # Skip rows containing any of the excluded phrases
                        if any(phrase in cleaned_text for phrase in phrases_to_exclude):
                            continue

                        # Only write rows where the cleaned text is not empty
                        if cleaned_text.strip():
                            writer.writerow([cleaned_text])
                    else:
                        continue  # Skip rows where the column index is out of range

            cleaned_files.append(output_file)

        return cleaned_files

    @staticmethod
    def unwrap_feedback_data_clean_tool(input_files: List[str], working_path: str):
        """
        Clean the unwrap user feedback data files provided as input, and output the specified column to new intermediate files.
        Args:
            input_files (List[str]): List of input CSV file paths generated by the previous tool.
        Returns:
            List[str]: List of generated intermediate file paths.
        """

        cleaned_files = []
        for file_path in input_files:
            base_name = os.path.splitext(os.path.basename(file_path))[0]
            output_file = os.path.join(working_path, f"{base_name}_cleaned_intermediate.csv")

            with open(file_path, 'r', encoding='utf-8') as infile, open(output_file, 'w', newline='', encoding='utf-8') as outfile:
                reader = csv.reader(infile)
                writer = csv.writer(outfile)

                header = next(reader, None)
                entry_text_index = UNWRAP_DEFAULT_COLUMN_INDEX
                sentiment_index = None

                # Identify the "Sentiment" column index
                if header:
                    if "Sentiment" in header:
                        sentiment_index = header.index("Sentiment")
                    if UNWRAP_COLUMN_NAME in header:
                        entry_text_index = header.index(UNWRAP_COLUMN_NAME)

                    # Write the header to the output file
                    writer.writerow([UNWRAP_COLUMN_NAME])

                for row in reader:
                    # Skip rows where the "Sentiment" column is "Positive"
                    if sentiment_index is not None and len(row) > sentiment_index and row[sentiment_index] == "Positive":
                        continue

                    # Extract and clean the specific column
                    if len(row) > entry_text_index:
                        cleaned_text = FileUtils.replace_stop_words(row[entry_text_index])
                        writer.writerow([cleaned_text])
                    else:
                        writer.writerow([""])

            cleaned_files.append(output_file)

        return cleaned_files

    @staticmethod
    def merge_feedback_data_clean_tool(input_files: List[str], working_path: str):
        """
        Merge the intermediate data files generated by unwrap_feedback_data_clean_tool and ocv_feedback_data_clean_tool.
        Args:
            input_files (List[str]): List of input CSV file paths generated by the previous tools.
        Returns:
            str: Path to the merged output file.
        """
        # Define the output file path
        output_file = os.path.join(working_path, "merged_intermediate.csv")

        # Check if input files are provided
        if not input_files or len(input_files) < 2:
            return "Error: At least two input files are required for merging."

        try:
            # Open the output file for writing
            with open(output_file, 'w', newline='', encoding='utf-8') as outfile:
                writer = csv.writer(outfile)

                for file_path in input_files:
                    # Ensure the file has the "_intermediate.csv" suffix
                    if not file_path.endswith("_cleaned_intermediate.csv"):
                        return f"Error: Invalid file format. Expected '_cleaned_intermediate.csv' but got {file_path}"

                    # Read each input file and append its content to the output file
                    with open(file_path, 'r', encoding='utf-8') as infile:
                        reader = csv.reader(infile)
                        for row in reader:
                            writer.writerow(row)

        except Exception as e:
            return f"Error during merging: {str(e)}"

        return output_file
