import streamlit as st
import pandas as pd

"""Self-defined utility functions for multiple pages in the Streamlit app."""

@st.cache_data
def get_data():
    """
    Reads the Netflix dataset from a CSV file, stores it in session state,
    and returns the DataFrame.

    Returns:
        pd.DataFrame: Netflix dataset.
    """
    csv_file = "./netflix_titles.csv"

    st.info(f"Reading data from file: {csv_file}")
    try:
        df = pd.read_csv(csv_file)
        st.session_state.df = df.copy()  # Store a copy in session state
        return df
    except FileNotFoundError:
        st.error(f"File not found: {csv_file}")
        return pd.DataFrame()  # Return an empty DataFrame if the file is missing


def check_page_prerequisites(n=1):
    """
    Checks whether the previous `n` steps of the app workflow have been completed.

    Parameters:
        n (int): Number of previous steps to check.

    Returns:
        bool: True if the prerequisites are met, False otherwise.
    """
    if "steps" in st.session_state:
        steps = st.session_state.get("steps", [])
        for i in range(1, n + 1):
            if i not in steps:
                return False
        return True
    else:
        st.warning("Session state is missing `steps`. Please start from the main page.")
        return False


def add_page_number(n):
    """
    Adds a page number to `st.session_state.steps`.

    Parameters:
        n (int): Page number to add.

    Returns:
        bool: False if `n` is already in steps, True otherwise.
    """
    if "steps" not in st.session_state:
        st.session_state.steps = []

    if n not in st.session_state.steps:
        st.session_state.steps.append(n)
        return True

    return False


def save_data_to_file(df, file_name="augmented_netflix_titles.csv"):
    """
    Saves the given DataFrame to a CSV file.

    Parameters:
        df (pd.DataFrame): DataFrame to save.
        file_name (str): Output file name.
    """
    try:
        df.to_csv(file_name, index=False)
        st.success(f"Data saved successfully to {file_name}")
    except Exception as e:
        st.error(f"Failed to save data: {e}")