import { createClient } from '@supabase/supabase-js'; import * as path from 'path'; import * as dotenv from 'dotenv'; import * as fs from 'fs'; // Load environment variables from .env.local const envLocalPath = path.resolve(process.cwd(), '.env.local'); if (fs.existsSync(envLocalPath)) { console.log(`Loading environment from: ${envLocalPath}`); dotenv.config({ path: envLocalPath }); } else { console.log(`No .env.local file found at: ${envLocalPath}`); dotenv.config(); // Try loading from default .env } // Helper function to normalize URLs for comparison function normalizeUrl(url: string): string { return url.trim() .toLowerCase() .replace(/^https?:\/\/(www\.)?/, '') // Remove protocol and www .replace(/\/+$/, '') // Remove trailing slashes .replace(/\?.*$/, ''); // Remove query parameters } async function main() { // Check for required environment variables const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseServiceKey) { console.error('Error: Missing required environment variables NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY'); process.exit(1); } // Initialize Supabase client const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { autoRefreshToken: false, persistSession: false } }); try { console.log('Fetching all news items...'); // Fetch all news items const { data: allNews, error: fetchError } = await supabase .from('news') .select('id, title, url, source, article_date, created_at') .order('article_date', { ascending: false }); if (fetchError) { console.error('Error fetching news items:', fetchError); return; } if (!allNews || allNews.length === 0) { console.log('No news items found.'); return; } console.log(`Found ${allNews.length} news items.`); // Create maps to track duplicates const normalizedUrlMap = new Map(); const titleSourceMap = new Map(); const duplicateIds = new Set(); // First pass: identify duplicates for (const news of allNews) { const normalizedUrl = normalizeUrl(news.url); const titleSourceKey = `${news.title.toLowerCase().trim()}|${news.source.toLowerCase().trim()}`; // Check for URL duplicates if (normalizedUrlMap.has(normalizedUrl)) { const existing = normalizedUrlMap.get(normalizedUrl); // Keep the newer item (based on article_date, then created_at) const existingDate = new Date(existing.article_date || existing.created_at); const currentDate = new Date(news.article_date || news.created_at); if (existingDate >= currentDate) { duplicateIds.add(news.id); console.log(`Duplicate URL found: "${news.title}" (ID: ${news.id}) is a duplicate of ID: ${existing.id}`); } else { duplicateIds.add(existing.id); normalizedUrlMap.set(normalizedUrl, news); console.log(`Duplicate URL found: "${existing.title}" (ID: ${existing.id}) is a duplicate of ID: ${news.id}`); } } else { normalizedUrlMap.set(normalizedUrl, news); } // Check for title+source duplicates (if not already marked as duplicate) if (!duplicateIds.has(news.id) && titleSourceMap.has(titleSourceKey)) { const existing = titleSourceMap.get(titleSourceKey); // Skip if this is the same item we already processed by URL if (existing.id === news.id) continue; // Keep the newer item (based on article_date, then created_at) const existingDate = new Date(existing.article_date || existing.created_at); const currentDate = new Date(news.article_date || news.created_at); if (existingDate >= currentDate) { duplicateIds.add(news.id); console.log(`Duplicate title+source found: "${news.title}" (ID: ${news.id}) is a duplicate of ID: ${existing.id}`); } else { duplicateIds.add(existing.id); titleSourceMap.set(titleSourceKey, news); console.log(`Duplicate title+source found: "${existing.title}" (ID: ${existing.id}) is a duplicate of ID: ${news.id}`); } } else if (!duplicateIds.has(news.id)) { titleSourceMap.set(titleSourceKey, news); } } // Second pass: check for similar URLs for (const news of allNews) { // Skip if already marked as duplicate if (duplicateIds.has(news.id)) continue; const normalizedUrl = normalizeUrl(news.url); // Check for similar URLs for (const [existingNormalized, existing] of normalizedUrlMap.entries()) { // Skip if it's the same news item or if existing is already a duplicate if (existing.id === news.id || duplicateIds.has(existing.id)) continue; // Skip if it's an exact match (already handled) if (existingNormalized === normalizedUrl) continue; // Check for partial matches if (existingNormalized.includes(normalizedUrl) || normalizedUrl.includes(existingNormalized)) { // Keep the newer item (based on article_date, then created_at) const existingDate = new Date(existing.article_date || existing.created_at); const currentDate = new Date(news.article_date || news.created_at); if (existingDate >= currentDate) { duplicateIds.add(news.id); console.log(`Similar URL found: "${news.title}" (ID: ${news.id}) is similar to ID: ${existing.id}`); console.log(` URL 1: ${news.url}`); console.log(` URL 2: ${existing.url}`); break; } else { duplicateIds.add(existing.id); console.log(`Similar URL found: "${existing.title}" (ID: ${existing.id}) is similar to ID: ${news.id}`); console.log(` URL 1: ${existing.url}`); console.log(` URL 2: ${news.url}`); // Update the map with the newer item normalizedUrlMap.set(existingNormalized, news); } } } } console.log(`Found ${duplicateIds.size} duplicate news items.`); if (duplicateIds.size === 0) { console.log('No duplicates to remove.'); return; } // Confirm before deleting console.log('Deleting duplicate news items...'); // Delete news_categories entries for duplicates const { error: deleteJunctionError } = await supabase .from('news_categories') .delete() .in('news_id', Array.from(duplicateIds)); if (deleteJunctionError) { console.error('Error deleting news_categories entries:', deleteJunctionError); } else { console.log('Deleted news_categories entries for duplicates.'); } // Delete duplicate news items const { error: deleteNewsError } = await supabase .from('news') .delete() .in('id', Array.from(duplicateIds)); if (deleteNewsError) { console.error('Error deleting duplicate news items:', deleteNewsError); } else { console.log(`Successfully deleted ${duplicateIds.size} duplicate news items.`); } // Get final count const { count, error: countError } = await supabase .from('news') .select('*', { count: 'exact', head: true }); if (countError) { console.error('Error getting final count:', countError); } else { console.log(`Final news item count: ${count}`); } console.log('Duplicate removal completed successfully!'); } catch (error) { console.error('Error removing duplicates:', error); throw error; } } // Run the function main() .then(() => { console.log('Process completed successfully'); process.exit(0); }) .catch((error) => { console.error('Process failed:', error); process.exit(1); });