from typing import Union
from pathlib import Path
import logging

import pandas as pd
from statsmodels.iolib.summary import Summary
from statsmodels.regression.linear_model import RegressionResults


def print_and_save_result(
    print_result: bool,
    save_result: bool,
    filepath: str,
    result: Union[str, Summary, RegressionResults, pd.DataFrame],
    name_save_file: Path,
) -> None:
    """
    Prints and/or saves the analysis result based on the specified conditions.

    This function is designed to handle the output of statistical analysis results, allowing for both printing to the
    console and saving to a file. The type of the result (e.g., string, DataFrame) determines the format of the saved file.
    Logging is used to record the result in a consistent format, facilitating debugging and record-keeping.

    Parameters
    ----------
    print_result : bool
        A flag indicating whether to print the result to the console.
    save_result : bool
        A flag indicating whether to save the result to a file.
    filepath : str
        The base path where the result file will be saved. It is used in conjunction with `name_save_file`
        to construct the full file path.
    result : Union[str, Summary, RegressionResults, pd.DataFrame]
        The result of the analysis. Can be a string, a Summary object, a RegressionResults object, or a pandas DataFrame
    name_save_file : Path
        The name of the file (without extension) to which the result will be saved.
        The extension is determined by the type of `result`.

    Returns
    -------
    None
    """
    pd.set_option('display.max_columns', None)
    pd.set_option('display.width', 1000)

    if isinstance(result, pd.DataFrame):
        result_str = result.to_markdown()
        logging.info(result_str)
    else:
        result_str = str(result)
        logging.info("```")
        logging.info(result_str)
        logging.info("```")

    if print_result:
        print(result_str)
    if save_result:
        if type(result) == pd.DataFrame:
            result.to_csv(f"{filepath}{name_save_file}.csv", index=True)

        else:
            with open(f"{filepath}{name_save_file}.txt", "w") as f:
                f.write(result_str)
