import pandas as pd
import numpy as np

# Load the dataset
df = pd.read_csv("Mock_Habit_and_RENSS_Data_for_20_Participants.csv")

# Convert date to datetime for proper ordering
df['Date'] = pd.to_datetime(df['Date'])

# Let's create a dataframe that shows habit adherence across days by object placement
# Convert categorical variables to numeric for analysis
df['HabitPerformed_Numeric'] = df['HabitPerformed'].map({'Yes': 1, 'No': 0})
df['ObjectInPosition_Numeric'] = df['ObjectInPosition'].map({'Yes': 1, 'No': 0})

# Group by participant and calculate adherence rate and object placement rate
participant_summary = df.groupby('Participant').agg({
    'HabitPerformed_Numeric': 'mean',
    'ObjectInPosition_Numeric': 'mean'
}).reset_index()

participant_summary.rename(columns={
    'HabitPerformed_Numeric': 'Habit_Adherence_Rate',
    'ObjectInPosition_Numeric': 'Object_Placement_Rate'
}, inplace=True)

# Calculate correlation between habit adherence and object placement
correlation = np.corrcoef(
    participant_summary['Habit_Adherence_Rate'],
    participant_summary['Object_Placement_Rate']
)[0, 1]

print("Correlation between habit adherence and object placement: {:.3f}".format(correlation))
print("\nParticipant summary (habit adherence vs object placement):")
print(participant_summary)

# Save for later use
participant_summary.to_csv("participant_summary.csv", index=False)

# Create a dataframe that shows the day-by-day relationship
# First, let's create a day number column for easier plotting
df['Day_Number'] = df['Date'].dt.day - df['Date'].dt.day.min() + 1

# Calculate daily habit performance rate when object is in position vs not
daily_comparison = df.groupby(['Day_Number', 'ObjectInPosition'])['HabitPerformed_Numeric'].mean().reset_index()
daily_comparison.rename(columns={'HabitPerformed_Numeric': 'Habit_Completion_Rate'}, inplace=True)

print("\nDaily habit completion rate by object position:")
print(daily_comparison)

# Save for later use
daily_comparison.to_csv("daily_comparison.csv", index=False)

# Now let's calculate RENSS scores over time
# Calculate total RENSS score for each participant on each day
df['RENSS_Total'] = df.iloc[:, 4:16].sum(axis=1)  # Columns RENSS_1 to RENSS_12

# Group by day and habit performance
renss_by_habit = df.groupby(['Day_Number', 'HabitPerformed'])['RENSS_Total'].mean().reset_index()

print("\nAverage RENSS score by day and habit performance:")
print(renss_by_habit)

# Save for later use
renss_by_habit.to_csv("renss_by_habit.csv", index=False)

# Now let's look at the relationship between object placement and RENSS scores
renss_by_object = df.groupby(['Day_Number', 'ObjectInPosition'])['RENSS_Total'].mean().reset_index()

print("\nAverage RENSS score by day and object placement:")
print(renss_by_object)

# Save for later use
renss_by_object.to_csv("renss_by_object.csv", index=False)