Branchwell

AI Resource Pro / website / scripts / cleanup-orphaned-junctions.ts

1import { createClient } from '@supabase/supabase-js';
2import * as dotenv from 'dotenv';
3import * as path from 'path';
4import * as fs from 'fs';
5
6// Load environment variables
7const envLocalPath = path.resolve(process.cwd(), '../.env.local');
8if (fs.existsSync(envLocalPath)) {
9 console.log(`Loading environment from: ${envLocalPath}`);
10 dotenv.config({ path: envLocalPath });
11} else {
12 console.log(`No .env.local file found at: ${envLocalPath}`);
13 dotenv.config();
14}
15
16async function cleanupOrphanedJunctions() {
17 const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
18 const supabaseKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
19
20 if (!supabaseUrl || !supabaseKey) {
21 console.error('Missing Supabase environment variables');
22 process.exit(1);
23 }
24
25 const supabase = createClient(supabaseUrl, supabaseKey);
26
27 console.log('Identifying orphaned junction entries...');
28
29 // Get all valid tool IDs
30 const { data: tools } = await supabase
31 .from('tools')
32 .select('id');
33
34 if (!tools || tools.length === 0) {
35 console.log('No tools found in database');
36 return;
37 }
38
39 const validToolIds = new Set(tools.map(t => t.id));
40 console.log(`Found ${validToolIds.size} valid tool IDs in database`);
41
42 // Get all junction entries
43 const { data: junctions } = await supabase
44 .from('tools_categories')
45 .select('*');
46
47 if (!junctions) {
48 console.log('No junction entries found');
49 return;
50 }
51
52 // Identify orphaned entries
53 const orphanedJunctions = junctions.filter(j => !validToolIds.has(j.tool_id));
54 console.log(`Found ${orphanedJunctions.length} orphaned junction entries out of ${junctions.length} total`);
55
56 if (orphanedJunctions.length === 0) {
57 console.log('No orphaned entries to clean up');
58 return;
59 }
60
61 // Group by category to understand which categories are affected
62 const orphansByCategory: Record<number, number> = {};
63 for (const j of orphanedJunctions) {
64 orphansByCategory[j.category_id] = (orphansByCategory[j.category_id] || 0) + 1;
65 }
66
67 console.log('\nOrphaned entries by category:');
68 for (const [categoryId, count] of Object.entries(orphansByCategory)) {
69 const { data: category } = await supabase
70 .from('categories')
71 .select('name')
72 .eq('id', categoryId)
73 .single();
74
75 const categoryName = category ? category.name : 'Unknown';
76 console.log(`- Category ${categoryId} (${categoryName}): ${count} orphaned entries`);
77 }
78
79 console.log('\n===== RECOMMENDED ACTIONS =====');
80 console.log('1. Clean up orphaned entries (this requires writing to the database)');
81 console.log('2. Associate existing tools with category 61 (LLMs)');
82
83 // Find potential LLM tools to associate with category 61
84 console.log('\nPotential tools to associate with category 61 (LLMs):');
85 const { data: llmTools } = await supabase
86 .from('tools')
87 .select('id, name, published')
88 .or('name.ilike.%llm%,name.ilike.%language model%,name.ilike.%gpt%,name.ilike.%claude%,name.ilike.%gemini%,name.ilike.%llama%')
89 .eq('published', true);
90
91 if (llmTools && llmTools.length > 0) {
92 for (const tool of llmTools) {
93 console.log(`- ${tool.name} (ID: ${tool.id})`);
94
95 // Check which categories this tool is already in
96 const { data: toolCategories } = await supabase
97 .from('tools_categories')
98 .select('category_id')
99 .eq('tool_id', tool.id);
100
101 if (toolCategories && toolCategories.length > 0) {
102 const categoryIds = toolCategories.map(tc => tc.category_id);
103 console.log(` Currently in categories: ${categoryIds.join(', ')}`);
104
105 // Get category names
106 for (const catId of categoryIds) {
107 const { data: category } = await supabase
108 .from('categories')
109 .select('name')
110 .eq('id', catId)
111 .single();
112
113 if (category) {
114 console.log(` - Category ${catId}: ${category.name}`);
115 }
116 }
117 } else {
118 console.log(' Not associated with any categories');
119 }
120 }
121 } else {
122 console.log('No potential LLM tools found');
123 }
124
125 console.log('\nTo clean up orphaned entries, run this script with --execute flag');
126 console.log('Example: npx ts-node cleanup-orphaned-junctions.ts --execute');
127
128 // Check if --execute flag is provided
129 if (process.argv.includes('--execute')) {
130 console.log('\n===== EXECUTING CLEANUP =====');
131 console.log('Deleting orphaned junction entries...');
132
133 // Get IDs of orphaned junctions
134 const orphanedIds = orphanedJunctions.map(j => j.id);
135
136 // Delete in batches of 10 to avoid potential issues
137 for (let i = 0; i < orphanedIds.length; i += 10) {
138 const batch = orphanedIds.slice(i, i + 10);
139 console.log(`Deleting batch ${i/10 + 1} (${batch.length} entries)...`);
140
141 const { error } = await supabase
142 .from('tools_categories')
143 .delete()
144 .in('id', batch);
145
146 if (error) {
147 console.error(`Error deleting batch: ${error.message}`);
148 } else {
149 console.log(`Successfully deleted batch ${i/10 + 1}`);
150 }
151 }
152
153 console.log('Cleanup completed');
154 }
155
156 console.log('\nTo associate tools with category 61 (LLMs), run:');
157 console.log('npx ts-node associate-tools-with-llms.ts');
158}
159
160cleanupOrphanedJunctions().catch(console.error);