Clear all statistics data and reset to default empty state

Completely erases all collected listening statistics and reinitializes the statistics store with empty default values. This function is typically used when the user wants to reset their listening history or when data integrity issues require a fresh start.

The function:

  • Creates a new default statistics object with the current timestamp
  • Ensures the target directory exists
  • Deletes all statistics files except the main one
  • Resets the main statistics file with default empty values
  • Triggers a manual aggregation to regenerate all statistics files
  • Handles any errors that occur during the reset operation
// Reset all statistics
const success = await clearStatistics();
if (success) {
showNotification("Statistics have been reset");
} else {
showErrorMessage("Failed to reset statistics");
}
export const clearStatistics = async (): Promise<boolean> => {
try {
// Create a fresh default statistics object with current timestamp
const freshDefault = {
...defaultStatisticsData,
lastUpdated: new Date().toISOString(),
};

// Make sure main data directory exists
await ensureDir(join(app.getPath("userData"), "data"));

// Make sure statistics directory exists
const statisticsDir = join(app.getPath("userData"), "data", "statistics");
await ensureDir(statisticsDir);

// Define all statistics files to clear
const statisticsFiles = [
// Main statistics file
statisticsFilePath,

// Additional metrics and patterns files in the statistics directory
join(statisticsDir, "daily_skip_metrics.json"),
join(statisticsDir, "weekly_skip_metrics.json"),
join(statisticsDir, "artist_skip_metrics.json"),
join(statisticsDir, "library_skip_statistics.json"),
join(statisticsDir, "time_based_patterns.json"),
join(statisticsDir, "detected_patterns.json"),
];

// Reset the main statistics file with default data
writeJsonSync(statisticsFilePath, freshDefault, { spaces: 2 });

// Delete all other statistics files instead of writing empty data
for (const filePath of statisticsFiles) {
if (filePath !== statisticsFilePath) {
// Skip the main file as it's already handled
try {
if (existsSync(filePath)) {
// Delete the file completely instead of writing empty data
removeSync(filePath);
}
} catch (fileError) {
// Log but continue with other files
console.warn(
`Could not delete statistics file ${filePath}:`,
fileError,
);
}
}
}

// Import and trigger statistics regeneration
try {
await triggerManualAggregation();
} catch (aggregationError) {
console.warn(
"Could not trigger statistics regeneration:",
aggregationError,
);
// Continue even if aggregation fails - files will be regenerated later
}

return true;
} catch (error) {
console.error("Error clearing statistics:", error);
return false;
}
};