import pathlib
from pathlib import Path
from typing import Optional

from fauxpy import constants
from fauxpy.constants import FileNames


class CollectPsRunSessionFileManager:
    """
    Manages file operations during Collect Ps Run session.
    """

    def __init__(self, report_directory_path: Path, project_working_directory: Path):
        """
        Initializes the file manager.

        Args:
            report_directory_path (Path): The directory where report files will be saved.
            project_working_directory (Path): The project's working directory path.
        """
        self._report_directory_path = report_directory_path
        self._project_working_directory = project_working_directory

    def save_test_case_table(self, json_table: str):
        """
        Saves the given JSON table of test cases to a file.

        Args:
            json_table (str): A JSON string representing the test case table.
        """
        temp = self._report_directory_path
        file_path = temp / constants.FileNames.collectModeTestCases
        with open(file_path, "w") as file:
            file.write(json_table)

    def save_seen_exception_sequence_table(self, json_table: str):
        """
        Saves the given JSON table of seen exceptions to a file.

        Args:
            json_table (str): A JSON string representing the seen exception sequence table.
        """
        file_path = (
            self._report_directory_path / constants.FileNames.collectModeSeenExceptions
        )
        with open(file_path, "w") as file:
            file.write(json_table)

    def load_seen_exception_sequence_and_remove_file(self) -> Optional[str]:
        """
        Loads the seen exception sequence file generated by the
        instrumentation library for the current execution,
        removes the file, and returns its content.

        Returns:
            Optional[str]: The content of the seen exception sequence file if it exists;
            otherwise, None if the file is missing or cannot be accessed.
        """
        file_path = self._project_working_directory / pathlib.Path(
            FileNames.instrumentationCollectModeExceptionSeenFileName
        )
        try:
            with open(file_path, "r") as file:
                seen_exp_sequence = file.read()
                if seen_exp_sequence[-1] == ",":
                    seen_exp_sequence = seen_exp_sequence[0:-1]
                return seen_exp_sequence
        except:
            return None
        finally:
            if file_path.exists():
                file_path.unlink()

    def remove_evaluation_counter_file(self):
        """
        Removes the file used for tracking the evaluation counter.

        This method deletes the evaluation counter file if it exists.
        """
        file_path = self._project_working_directory / pathlib.Path(
            FileNames.instrumentationCollectModeEvaluationCounterFileName
        )
        if file_path.exists():
            file_path.unlink()
