Branchwell

AI Resource Pro / website / scripts / consolidate-tags.mjs

1import { createClient } from '@supabase/supabase-js';
2import dotenv from 'dotenv';
3import fs from 'fs';
4import path from 'path';
5
6const envLocalPath = path.resolve(process.cwd(), '.env.local');
7if (fs.existsSync(envLocalPath)) {
8 dotenv.config({ path: envLocalPath });
9} else {
10 dotenv.config();
11}
12
13const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
14const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
15
16if (!supabaseUrl || !supabaseServiceKey) {
17 console.error('Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env.local');
18 process.exit(1);
19}
20
21const supabase = createClient(supabaseUrl, supabaseServiceKey, {
22 auth: { persistSession: false, autoRefreshToken: false },
23 db: { schema: 'public' },
24});
25
26const GENERIC_DELETE_NAMES = new Set([
27 'general ai',
28 'ai',
29 'artificial intelligence',
30 'ai tools',
31 'general',
32 'other',
33 'misc',
34 'miscellaneous',
35 'uncategorized',
36]);
37
38const EXPLICIT_MERGE_RULES = [
39 { canonical: 'Code Generation', aliases: ['code generation', 'code assistant', 'coding tools'] },
40 { canonical: 'Developer Tools', aliases: ['dev tools', 'developer tools', 'development tools'] },
41 { canonical: 'Data Science', aliases: ['data analysis', 'data science'] },
42 { canonical: 'Natural Language Processing', aliases: ['nlp', 'natural language processing'] },
43 { canonical: 'Machine Learning', aliases: ['ml', 'machine learning'] },
44 { canonical: 'Deep Learning', aliases: ['dl', 'deep learning'] },
45 { canonical: 'Courses', aliases: ['course', 'courses'] },
46 { canonical: 'Tutorials', aliases: ['tutorial', 'tutorials'] },
47];
48
49const COLLECTION_PLURAL_BASES = new Set([
50 'course',
51 'tutorial',
52 'chatbot',
53 'agent',
54 'api',
55 'tool',
56 'framework',
57 'model',
58 'resource',
59 'dataset',
60 'plugin',
61 'extension',
62]);
63
64const INFERENCE_KEYWORDS = {
65 'code generation': ['code', 'coding', 'programming', 'copilot', 'cursor', 'refactor', 'debug'],
66 'developer tools': ['sdk', 'cli', 'developer', 'devops', 'integration', 'api'],
67 'data science': ['data science', 'analytics', 'analysis', 'statistics', 'dashboard', 'notebook'],
68 'natural language processing': ['nlp', 'language processing', 'text analysis', 'sentiment', 'entity extraction', 'semantic'],
69 'machine learning': ['machine learning', 'ml', 'model training', 'classification', 'regression', 'prediction'],
70 'deep learning': ['deep learning', 'neural network', 'transformer', 'cnn', 'rnn'],
71 'courses': ['course', 'curriculum', 'class', 'bootcamp', 'certification'],
72 'tutorials': ['tutorial', 'guide', 'walkthrough', 'how to', 'step by step'],
73 'documentation': ['documentation', 'docs', 'reference', 'manual', 'quickstart'],
74 'chatbots': ['chatbot', 'assistant', 'conversation', 'conversational'],
75 'prompt engineering': ['prompt', 'system prompt', 'few-shot', 'instruction'],
76 'image generation': ['image generation', 'text to image', 'midjourney', 'stable diffusion', 'dall-e'],
77 'video generation': ['video generation', 'text to video', 'sora', 'runway'],
78 'audio generation': ['audio generation', 'music generation', 'voice generation', 'sound design'],
79 'speech recognition': ['speech recognition', 'speech to text', 'stt', 'transcription', 'asr'],
80 'text-to-speech': ['text to speech', 'tts', 'speech synthesis', 'voice synthesis'],
81 'workflow automation': ['workflow', 'automation', 'zapier', 'n8n', 'make.com', 'pipeline'],
82 search: ['search', 'retrieval', 'rag', 'semantic search', 'vector search'],
83 research: ['research', 'paper', 'arxiv', 'benchmark', 'study', 'evaluation'],
84 apis: ['api', 'endpoint', 'webhook', 'rest api'],
85 'open source': ['open source', 'github', 'gitlab', 'oss'],
86 'computer vision': ['computer vision', 'image recognition', 'object detection', 'segmentation', 'ocr'],
87};
88
89const FALLBACK_BY_KIND = {
90 tools: ['Developer Tools', 'Code Generation', 'Machine Learning'],
91 news: ['Machine Learning', 'Data Science', 'Natural Language Processing'],
92 posts: ['Tutorials', 'Documentation', 'Machine Learning'],
93 learning: ['Courses', 'Tutorials', 'Machine Learning'],
94};
95
96const CONTENT_CANDIDATES = [
97 {
98 kind: 'tools',
99 itemTableCandidates: ['tools'],
100 junctionTableCandidates: ['tools_categories'],
101 itemIdColumnCandidates: ['tool_id'],
102 textColumnCandidates: ['description', 'content'],
103 nameColumnCandidates: ['name', 'title'],
104 },
105 {
106 kind: 'news',
107 itemTableCandidates: ['news', 'news_stories'],
108 junctionTableCandidates: ['news_categories'],
109 itemIdColumnCandidates: ['news_id', 'news_story_id'],
110 textColumnCandidates: ['content', 'description'],
111 nameColumnCandidates: ['title', 'name'],
112 },
113 {
114 kind: 'posts',
115 itemTableCandidates: ['posts', 'blog_posts'],
116 junctionTableCandidates: ['posts_categories', 'post_categories', 'blog_posts_categories'],
117 itemIdColumnCandidates: ['post_id', 'blog_post_id', 'posts_id'],
118 textColumnCandidates: ['content', 'description', 'summary'],
119 nameColumnCandidates: ['title', 'name'],
120 },
121 {
122 kind: 'learning',
123 itemTableCandidates: ['learning', 'learning_resources'],
124 junctionTableCandidates: ['learning_categories', 'learning_resources_categories'],
125 itemIdColumnCandidates: ['learning_id', 'learning_resource_id'],
126 textColumnCandidates: ['description', 'content', 'summary'],
127 nameColumnCandidates: ['title', 'name'],
128 },
129];
130
131function normalize(value) {
132 return String(value || '').trim().toLowerCase();
133}
134
135function slugify(value) {
136 return String(value || '')
137 .toLowerCase()
138 .replace(/[^a-z0-9]+/g, '-')
139 .replace(/(^-|-$)+/g, '')
140 .slice(0, 80);
141}
142
143function isMissingRelationError(error) {
144 const msg = normalize(error?.message || '');
145 return (
146 msg.includes('does not exist') ||
147 msg.includes('could not find the table') ||
148 msg.includes('schema cache') ||
149 msg.includes('relation')
150 );
151}
152
153function isMissingColumnError(error) {
154 const msg = normalize(error?.message || '');
155 return msg.includes('column') || msg.includes('schema cache');
156}
157
158function isDuplicateError(error) {
159 const msg = normalize(error?.message || '');
160 return msg.includes('duplicate key') || msg.includes('unique constraint');
161}
162
163async function fetchAllRows(table, columns) {
164 const pageSize = 1000;
165 const rows = [];
166 let from = 0;
167
168 while (true) {
169 const to = from + pageSize - 1;
170 const { data, error } = await supabase.from(table).select(columns).range(from, to);
171 if (error) throw new Error(`Failed to fetch ${table}: ${error.message}`);
172 if (!data || data.length === 0) break;
173 rows.push(...data);
174 if (data.length < pageSize) break;
175 from += pageSize;
176 }
177
178 return rows;
179}
180
181async function detectTable(candidates) {
182 for (const table of candidates) {
183 const { error } = await supabase.from(table).select('id').limit(1);
184 if (!error) return table;
185 if (isMissingRelationError(error)) continue;
186 throw new Error(`Unexpected error detecting table ${table}: ${error.message}`);
187 }
188 return null;
189}
190
191async function detectColumn(table, candidates) {
192 for (const col of candidates) {
193 const { error } = await supabase.from(table).select(col).limit(1);
194 if (!error) return col;
195 if (isMissingColumnError(error)) continue;
196 throw new Error(`Unexpected error detecting column ${table}.${col}: ${error.message}`);
197 }
198 return null;
199}
200
201async function detectExistingColumns(table, candidates) {
202 const found = [];
203 for (const col of candidates) {
204 const { error } = await supabase.from(table).select(col).limit(1);
205 if (!error) {
206 found.push(col);
207 continue;
208 }
209 if (isMissingColumnError(error)) continue;
210 throw new Error(`Unexpected error detecting column ${table}.${col}: ${error.message}`);
211 }
212 return found;
213}
214
215function pickBestCanonical(categories) {
216 const scored = [...categories].sort((a, b) => {
217 const aName = String(a.name || '');
218 const bName = String(b.name || '');
219 const aLower = normalize(aName);
220 const bLower = normalize(bName);
221
222 const aScore = (aName === aName.toUpperCase() ? -1 : 0) + aName.length + aName.split(/\s+/).length;
223 const bScore = (bName === bName.toUpperCase() ? -1 : 0) + bName.length + bName.split(/\s+/).length;
224
225 if (aScore !== bScore) return bScore - aScore;
226 if (aLower !== bLower) return aLower.localeCompare(bLower);
227 return Number(a.id) - Number(b.id);
228 });
229
230 return scored[0];
231}
232
233function singularBase(name) {
234 const n = normalize(name);
235 if (!n || n.includes(' ')) return null;
236 if (n.endsWith('ies') && n.length > 3) return `${n.slice(0, -3)}y`;
237 if (n.endsWith('s') && !n.endsWith('ss') && n.length > 2) return n.slice(0, -1);
238 return n;
239}
240
241function scoreCategory(category, text) {
242 const name = normalize(category.name);
243 const slug = normalize(category.slug || '');
244 const textLower = text;
245
246 let score = 0;
247 if (name && textLower.includes(name)) score += 8;
248
249 const nameTokens = name.split(/[^a-z0-9]+/).filter((t) => t.length > 2);
250 for (const token of nameTokens) {
251 if (textLower.includes(token)) score += 1;
252 }
253
254 const slugTokens = slug.split(/[^a-z0-9]+/).filter((t) => t.length > 2);
255 for (const token of slugTokens) {
256 if (textLower.includes(token)) score += 1;
257 }
258
259 const keywordList = INFERENCE_KEYWORDS[name] || [];
260 for (const keyword of keywordList) {
261 if (textLower.includes(normalize(keyword))) score += keyword.includes(' ') ? 4 : 2;
262 }
263
264 return score;
265}
266
267function uniqueByNormalize(names) {
268 const seen = new Set();
269 const output = [];
270 for (const name of names) {
271 const key = normalize(name);
272 if (!key || seen.has(key)) continue;
273 seen.add(key);
274 output.push(name);
275 }
276 return output;
277}
278
279async function detectSchema() {
280 const schemas = [];
281
282 for (const candidate of CONTENT_CANDIDATES) {
283 const itemTable = await detectTable(candidate.itemTableCandidates);
284 const junctionTable = await detectTable(candidate.junctionTableCandidates);
285 if (!itemTable || !junctionTable) continue;
286
287 const itemIdColumn = await detectColumn(junctionTable, candidate.itemIdColumnCandidates);
288 if (!itemIdColumn) continue;
289
290 const nameColumn = await detectColumn(itemTable, candidate.nameColumnCandidates);
291 if (!nameColumn) continue;
292
293 const textColumns = await detectExistingColumns(itemTable, candidate.textColumnCandidates);
294 const hasPrimaryCategoryId = !!(await detectColumn(itemTable, ['primary_category_id']));
295
296 schemas.push({
297 kind: candidate.kind,
298 itemTable,
299 junctionTable,
300 itemIdColumn,
301 nameColumn,
302 textColumns,
303 hasPrimaryCategoryId,
304 });
305 }
306
307 return schemas;
308}
309
310function buildCategoryState(categories) {
311 const byId = new Map();
312 const byName = new Map();
313 const bySlug = new Map();
314
315 for (const category of categories) {
316 byId.set(category.id, category);
317
318 const key = normalize(category.name);
319 if (!byName.has(key)) byName.set(key, []);
320 byName.get(key).push(category);
321
322 bySlug.set(normalize(category.slug || ''), category);
323 }
324
325 return { byId, byName, bySlug, categories };
326}
327
328async function ensureCategory(name, state, logs) {
329 const key = normalize(name);
330 const existing = state.byName.get(key);
331 if (existing && existing.length > 0) {
332 return pickBestCanonical(existing);
333 }
334
335 const baseSlug = slugify(name);
336 let slug = baseSlug;
337 let counter = 2;
338 while (state.bySlug.has(normalize(slug))) {
339 slug = `${baseSlug}-${counter}`;
340 counter += 1;
341 }
342
343 const payload = {
344 name,
345 slug,
346 icon: 'Tag',
347 description: `${name} resources and content`,
348 };
349
350 const { data, error } = await supabase
351 .from('categories')
352 .insert(payload)
353 .select('id, name, slug, icon, description')
354 .single();
355
356 if (error) {
357 throw new Error(`Failed to create canonical category ${name}: ${error.message}`);
358 }
359
360 state.categories.push(data);
361 state.byId.set(data.id, data);
362 state.bySlug.set(normalize(data.slug), data);
363 state.byName.set(key, [data]);
364
365 logs.createdCategories.push({ id: data.id, name: data.name, slug: data.slug });
366 return data;
367}
368
369function addMergeMapping(mappings, fromCategory, toCategory, reason) {
370 if (!fromCategory) return;
371 if (toCategory && fromCategory.id === toCategory.id) return;
372
373 const existing = mappings.get(fromCategory.id);
374 if (existing) {
375 if (existing.toId === null) return;
376 if (toCategory && existing.toId !== toCategory.id) {
377 return;
378 }
379 }
380
381 mappings.set(fromCategory.id, {
382 fromId: fromCategory.id,
383 fromName: fromCategory.name,
384 toId: toCategory ? toCategory.id : null,
385 toName: toCategory ? toCategory.name : null,
386 reason,
387 });
388}
389
390async function buildMergePlan(state, logs) {
391 const mappings = new Map();
392
393 for (const category of state.categories) {
394 const n = normalize(category.name);
395 if (GENERIC_DELETE_NAMES.has(n)) {
396 addMergeMapping(mappings, category, null, 'generic category deletion list');
397 }
398 }
399
400 for (const [nameKey, categories] of state.byName.entries()) {
401 if (categories.length < 2) continue;
402 if (GENERIC_DELETE_NAMES.has(nameKey)) {
403 for (const category of categories) addMergeMapping(mappings, category, null, 'generic duplicate deletion');
404 continue;
405 }
406
407 const canonical = pickBestCanonical(categories);
408 for (const category of categories) {
409 if (category.id !== canonical.id) {
410 addMergeMapping(mappings, category, canonical, 'exact duplicate name (case/format variant)');
411 }
412 }
413 }
414
415 for (const rule of EXPLICIT_MERGE_RULES) {
416 const canonical = await ensureCategory(rule.canonical, state, logs);
417 const aliasSet = new Set(rule.aliases.map((a) => normalize(a)));
418
419 for (const category of state.categories) {
420 const n = normalize(category.name);
421 if (!aliasSet.has(n)) continue;
422 if (n === normalize(canonical.name) && category.id === canonical.id) continue;
423 addMergeMapping(mappings, category, canonical, `synonym/variant rule -> ${rule.canonical}`);
424 }
425 }
426
427 const byBase = new Map();
428 for (const category of state.categories) {
429 const base = singularBase(category.name);
430 if (!base || !COLLECTION_PLURAL_BASES.has(base)) continue;
431 if (!byBase.has(base)) byBase.set(base, []);
432 byBase.get(base).push(category);
433 }
434
435 for (const [base, categories] of byBase.entries()) {
436 if (categories.length < 2) continue;
437 const pluralName = `${base}s`;
438 const canonical =
439 categories.find((c) => normalize(c.name) === pluralName) ||
440 categories.find((c) => normalize(c.name) === `${base}ies`) ||
441 pickBestCanonical(categories);
442
443 for (const category of categories) {
444 if (category.id === canonical.id) continue;
445 addMergeMapping(mappings, category, canonical, `obvious singular/plural duplicate (${base})`);
446 }
447 }
448
449 return [...mappings.values()];
450}
451
452async function safeInsertLink(junctionTable, itemIdColumn, itemId, categoryId, isPrimary) {
453 const { data: existing, error: checkError } = await supabase
454 .from(junctionTable)
455 .select(`${itemIdColumn}, category_id, is_primary`)
456 .eq(itemIdColumn, itemId)
457 .eq('category_id', categoryId)
458 .limit(1);
459
460 if (checkError) throw new Error(`Failed checking existing link ${junctionTable}: ${checkError.message}`);
461
462 if (existing && existing.length > 0) {
463 if (isPrimary && !existing[0].is_primary) {
464 const { error: updateError } = await supabase
465 .from(junctionTable)
466 .update({ is_primary: true })
467 .eq(itemIdColumn, itemId)
468 .eq('category_id', categoryId);
469 if (updateError) throw new Error(`Failed promoting existing link to primary in ${junctionTable}: ${updateError.message}`);
470 }
471 return false;
472 }
473
474 const { error: insertError } = await supabase
475 .from(junctionTable)
476 .insert({ [itemIdColumn]: itemId, category_id: categoryId, is_primary: !!isPrimary });
477
478 if (insertError) {
479 if (isDuplicateError(insertError)) return false;
480 throw new Error(`Failed inserting link into ${junctionTable}: ${insertError.message}`);
481 }
482
483 return true;
484}
485
486async function moveJunctionLinks(schema, fromId, toId, logs) {
487 const rows = await fetchAllRows(schema.junctionTable, `${schema.itemIdColumn}, category_id, is_primary`);
488 const impacted = rows.filter((row) => row.category_id === fromId);
489 if (impacted.length === 0) return;
490
491 for (const row of impacted) {
492 const itemId = row[schema.itemIdColumn];
493
494 if (toId !== null) {
495 const inserted = await safeInsertLink(schema.junctionTable, schema.itemIdColumn, itemId, toId, !!row.is_primary);
496 if (inserted) logs.movedLinks += 1;
497 else logs.skippedDuplicateLinks += 1;
498 }
499
500 const { error: deleteError } = await supabase
501 .from(schema.junctionTable)
502 .delete()
503 .eq(schema.itemIdColumn, itemId)
504 .eq('category_id', fromId);
505
506 if (deleteError) {
507 throw new Error(`Failed deleting old link from ${schema.junctionTable}: ${deleteError.message}`);
508 }
509
510 logs.deletedLinks += 1;
511 }
512}
513
514async function updatePrimaryCategoryColumn(schema, fromId, toId, logs) {
515 if (!schema.hasPrimaryCategoryId) return;
516
517 if (toId === null) {
518 const { error } = await supabase
519 .from(schema.itemTable)
520 .update({ primary_category_id: null })
521 .eq('primary_category_id', fromId);
522
523 if (error) throw new Error(`Failed nulling ${schema.itemTable}.primary_category_id from ${fromId}: ${error.message}`);
524 logs.primaryCategoryUpdates += 1;
525 return;
526 }
527
528 const { error } = await supabase
529 .from(schema.itemTable)
530 .update({ primary_category_id: toId })
531 .eq('primary_category_id', fromId);
532
533 if (error) throw new Error(`Failed updating ${schema.itemTable}.primary_category_id from ${fromId} to ${toId}: ${error.message}`);
534 logs.primaryCategoryUpdates += 1;
535}
536
537function buildItemsById(rows) {
538 const map = new Map();
539 for (const row of rows) map.set(row.id, row);
540 return map;
541}
542
543function buildLinksByItem(links, itemIdColumn) {
544 const map = new Map();
545 for (const row of links) {
546 const itemId = row[itemIdColumn];
547 if (!map.has(itemId)) map.set(itemId, []);
548 map.get(itemId).push(row);
549 }
550 return map;
551}
552
553function getItemText(item, schema) {
554 const headline = String(item[schema.nameColumn] || '');
555 const body = schema.textColumns.map((col) => String(item[col] || '')).join('\n');
556 return `${headline}\n${body}`.toLowerCase().slice(0, 40000);
557}
558
559function inferCategoryCandidates({ item, schema, availableCategories }) {
560 const text = getItemText(item, schema);
561
562 const scored = [];
563 for (const category of availableCategories) {
564 const score = scoreCategory(category, text);
565 if (score > 0) scored.push({ category, score });
566 }
567
568 scored.sort((a, b) => b.score - a.score || Number(a.category.id) - Number(b.category.id));
569 return scored.map((entry) => entry.category.id);
570}
571
572async function ensureFallbackCategories(state, logs) {
573 const needed = uniqueByNormalize(Object.values(FALLBACK_BY_KIND).flat());
574 for (const name of needed) {
575 await ensureCategory(name, state, logs);
576 }
577}
578
579async function reconcileItemTags({ item, schema, linkRows, state, genericDeleteIds, logs }) {
580 const currentRows = linkRows || [];
581 const itemId = item.id;
582
583 const dedupCurrent = [];
584 const seenCurrent = new Set();
585 for (const row of currentRows) {
586 const key = `${row[schema.itemIdColumn]}::${row.category_id}`;
587 if (seenCurrent.has(key)) continue;
588 seenCurrent.add(key);
589 dedupCurrent.push(row);
590 }
591
592 const currentPrimaryRow = dedupCurrent.find((r) => !!r.is_primary);
593 const currentPrimaryId = currentPrimaryRow?.category_id || null;
594
595 const currentSpecificIds = dedupCurrent
596 .map((r) => r.category_id)
597 .filter((id) => !genericDeleteIds.has(id) && state.byId.has(id));
598
599 const availableCategories = state.categories.filter((c) => !genericDeleteIds.has(c.id));
600 const inferredIds = inferCategoryCandidates({ item, schema, availableCategories });
601
602 const finalIds = [];
603 const addFinal = (id) => {
604 if (!id) return;
605 if (finalIds.includes(id)) return;
606 if (!state.byId.has(id)) return;
607 if (genericDeleteIds.has(id)) return;
608 if (finalIds.length >= 5) return;
609 finalIds.push(id);
610 };
611
612 if (currentPrimaryId) addFinal(currentPrimaryId);
613 for (const id of currentSpecificIds) addFinal(id);
614 for (const id of inferredIds) {
615 addFinal(id);
616 if (finalIds.length >= 5) break;
617 }
618
619 if (finalIds.length < 3) {
620 const fallbackNames = FALLBACK_BY_KIND[schema.kind] || [];
621 for (const fallbackName of fallbackNames) {
622 const options = state.byName.get(normalize(fallbackName)) || [];
623 const cat = options[0];
624 if (!cat) continue;
625 addFinal(cat.id);
626 if (finalIds.length >= 3) break;
627 }
628 }
629
630 if (finalIds.length < 3) {
631 for (const category of availableCategories) {
632 addFinal(category.id);
633 if (finalIds.length >= 3) break;
634 }
635 }
636
637 if (finalIds.length > 5) {
638 finalIds.length = 5;
639 }
640
641 if (finalIds.length < 3) {
642 throw new Error(`Unable to assign at least 3 tags for ${schema.kind} id=${itemId}`);
643 }
644
645 let primaryId = null;
646 if (currentPrimaryId && finalIds.includes(currentPrimaryId)) {
647 primaryId = currentPrimaryId;
648 } else {
649 primaryId = inferredIds.find((id) => finalIds.includes(id)) || finalIds[0];
650 }
651
652 const finalSet = new Set(finalIds);
653 const currentSet = new Set(dedupCurrent.map((r) => r.category_id));
654
655 const toDelete = [...currentSet].filter((id) => !finalSet.has(id));
656 const toAdd = [...finalSet].filter((id) => !currentSet.has(id));
657
658 if (toDelete.length > 0) {
659 const { error } = await supabase
660 .from(schema.junctionTable)
661 .delete()
662 .eq(schema.itemIdColumn, itemId)
663 .in('category_id', toDelete);
664
665 if (error) throw new Error(`Failed deleting old tags for ${schema.kind} id=${itemId}: ${error.message}`);
666 logs.retag.removed += toDelete.length;
667 }
668
669 for (const categoryId of toAdd) {
670 const inserted = await safeInsertLink(schema.junctionTable, schema.itemIdColumn, itemId, categoryId, false);
671 if (inserted) logs.retag.added += 1;
672 }
673
674 const { error: clearPrimaryError } = await supabase
675 .from(schema.junctionTable)
676 .update({ is_primary: false })
677 .eq(schema.itemIdColumn, itemId);
678
679 if (clearPrimaryError) {
680 throw new Error(`Failed clearing primary flags for ${schema.kind} id=${itemId}: ${clearPrimaryError.message}`);
681 }
682
683 const { error: setPrimaryError } = await supabase
684 .from(schema.junctionTable)
685 .update({ is_primary: true })
686 .eq(schema.itemIdColumn, itemId)
687 .eq('category_id', primaryId);
688
689 if (setPrimaryError) {
690 throw new Error(`Failed setting primary tag for ${schema.kind} id=${itemId}: ${setPrimaryError.message}`);
691 }
692
693 if (schema.hasPrimaryCategoryId) {
694 const { error: primaryUpdateError } = await supabase
695 .from(schema.itemTable)
696 .update({ primary_category_id: primaryId })
697 .eq('id', itemId);
698
699 if (primaryUpdateError) {
700 throw new Error(`Failed updating ${schema.itemTable}.primary_category_id for id=${itemId}: ${primaryUpdateError.message}`);
701 }
702 }
703
704 const oldSorted = [...currentSet].sort((a, b) => a - b);
705 const newSorted = [...finalSet].sort((a, b) => a - b);
706 const changed =
707 oldSorted.length !== newSorted.length ||
708 oldSorted.some((value, index) => value !== newSorted[index]) ||
709 currentPrimaryId !== primaryId;
710
711 if (changed) {
712 logs.retag.itemsUpdated += 1;
713 logs.retag.details.push({
714 kind: schema.kind,
715 itemId,
716 itemLabel: item[schema.nameColumn],
717 oldCategoryIds: oldSorted,
718 newCategoryIds: newSorted,
719 oldPrimary: currentPrimaryId,
720 newPrimary: primaryId,
721 });
722 }
723}
724
725async function deleteCategoryIfUnreferenced(categoryId, categoryName, schemas, logs) {
726 for (const schema of schemas) {
727 const { data, error } = await supabase
728 .from(schema.junctionTable)
729 .select('category_id')
730 .eq('category_id', categoryId)
731 .limit(1);
732
733 if (error) throw new Error(`Failed checking references in ${schema.junctionTable}: ${error.message}`);
734 if (data && data.length > 0) {
735 logs.categoryDeleteSkipped.push({ id: categoryId, name: categoryName, reason: `still referenced in ${schema.junctionTable}` });
736 return;
737 }
738 }
739
740 for (const schema of schemas) {
741 if (!schema.hasPrimaryCategoryId) continue;
742 const { error } = await supabase
743 .from(schema.itemTable)
744 .update({ primary_category_id: null })
745 .eq('primary_category_id', categoryId);
746
747 if (error) {
748 throw new Error(`Failed nulling ${schema.itemTable}.primary_category_id for ${categoryId}: ${error.message}`);
749 }
750 }
751
752 const { error: deleteError } = await supabase.from('categories').delete().eq('id', categoryId);
753 if (deleteError) throw new Error(`Failed deleting category id=${categoryId} (${categoryName}): ${deleteError.message}`);
754
755 logs.categoryDeleted.push({ id: categoryId, name: categoryName });
756}
757
758async function main() {
759 const startedAt = new Date().toISOString();
760
761 const logs = {
762 startedAt,
763 schema: [],
764 createdCategories: [],
765 mergePlan: [],
766 movedLinks: 0,
767 deletedLinks: 0,
768 skippedDuplicateLinks: 0,
769 primaryCategoryUpdates: 0,
770 retag: {
771 itemsUpdated: 0,
772 added: 0,
773 removed: 0,
774 details: [],
775 },
776 categoryDeleted: [],
777 categoryDeleteSkipped: [],
778 };
779
780 console.log('Detecting schema...');
781 const schemas = await detectSchema();
782 if (schemas.length === 0) {
783 throw new Error('No compatible content/junction tables detected.');
784 }
785
786 logs.schema = schemas.map((s) => ({
787 kind: s.kind,
788 itemTable: s.itemTable,
789 junctionTable: s.junctionTable,
790 itemIdColumn: s.itemIdColumn,
791 nameColumn: s.nameColumn,
792 textColumns: s.textColumns,
793 hasPrimaryCategoryId: s.hasPrimaryCategoryId,
794 }));
795
796 for (const s of logs.schema) {
797 console.log(`- ${s.kind}: items=${s.itemTable}, junction=${s.junctionTable}, itemIdCol=${s.itemIdColumn}`);
798 }
799
800 const categories = await fetchAllRows('categories', 'id, name, slug, icon, description');
801 const state = buildCategoryState(categories);
802
803 console.log(`Loaded ${categories.length} categories.`);
804
805 await ensureFallbackCategories(state, logs);
806
807 const mergePlan = await buildMergePlan(state, logs);
808 logs.mergePlan = mergePlan;
809
810 const mergeOperations = mergePlan.filter((m) => m.toId !== null);
811 const genericDeleteIds = new Set(
812 mergePlan
813 .filter((m) => m.toId === null)
814 .map((m) => m.fromId),
815 );
816
817 console.log(`Merge operations: ${mergeOperations.length}`);
818 console.log(`Generic/delete operations: ${genericDeleteIds.size}`);
819
820 for (const op of mergeOperations) {
821 for (const schema of schemas) {
822 await moveJunctionLinks(schema, op.fromId, op.toId, logs);
823 await updatePrimaryCategoryColumn(schema, op.fromId, op.toId, logs);
824 }
825
826 await deleteCategoryIfUnreferenced(op.fromId, op.fromName, schemas, logs);
827 }
828
829 const categoriesAfterMerges = await fetchAllRows('categories', 'id, name, slug, icon, description');
830 const refreshedState = buildCategoryState(categoriesAfterMerges);
831
832 console.log('Re-auditing all content tags to enforce 3-5 tags and single primary...');
833
834 for (const schema of schemas) {
835 const itemFields = ['id', schema.nameColumn, ...schema.textColumns, schema.hasPrimaryCategoryId ? 'primary_category_id' : null]
836 .filter(Boolean)
837 .join(', ');
838 const items = await fetchAllRows(schema.itemTable, itemFields);
839 const links = await fetchAllRows(schema.junctionTable, `${schema.itemIdColumn}, category_id, is_primary`);
840
841 const itemsById = buildItemsById(items);
842 const linksByItem = buildLinksByItem(links, schema.itemIdColumn);
843
844 for (const [itemId, item] of itemsById.entries()) {
845 const itemLinks = linksByItem.get(itemId) || [];
846 await reconcileItemTags({
847 item,
848 schema,
849 linkRows: itemLinks,
850 state: refreshedState,
851 genericDeleteIds,
852 logs,
853 });
854 }
855
856 console.log(`- Retagged ${schema.kind}: processed ${items.length} items`);
857 }
858
859 console.log('Deleting generic/useless categories after retagging...');
860 for (const categoryId of genericDeleteIds) {
861 const category = refreshedState.byId.get(categoryId);
862 if (!category) continue;
863
864 for (const schema of schemas) {
865 const { error } = await supabase
866 .from(schema.junctionTable)
867 .delete()
868 .eq('category_id', categoryId);
869 if (error) throw new Error(`Failed removing residual generic links from ${schema.junctionTable}: ${error.message}`);
870
871 if (schema.hasPrimaryCategoryId) {
872 const { error: primaryError } = await supabase
873 .from(schema.itemTable)
874 .update({ primary_category_id: null })
875 .eq('primary_category_id', categoryId);
876 if (primaryError) throw new Error(`Failed nulling residual primary_category_id in ${schema.itemTable}: ${primaryError.message}`);
877 }
878 }
879
880 await deleteCategoryIfUnreferenced(categoryId, category.name, schemas, logs);
881 }
882
883 const finishedAt = new Date().toISOString();
884 logs.finishedAt = finishedAt;
885
886 const fileStamp = finishedAt.replace(/[:.]/g, '-');
887 const logPath = path.resolve(process.cwd(), 'logs', `consolidate-tags-${fileStamp}.json`);
888 fs.mkdirSync(path.dirname(logPath), { recursive: true });
889 fs.writeFileSync(logPath, JSON.stringify(logs, null, 2));
890
891 console.log('Consolidation complete.');
892 console.log(`Created categories: ${logs.createdCategories.length}`);
893 console.log(`Merged/deleted categories planned: ${logs.mergePlan.length}`);
894 console.log(`Moved links: ${logs.movedLinks}`);
895 console.log(`Deleted old links: ${logs.deletedLinks}`);
896 console.log(`Skipped duplicate links: ${logs.skippedDuplicateLinks}`);
897 console.log(`Items retagged: ${logs.retag.itemsUpdated}`);
898 console.log(`Tags added: ${logs.retag.added}`);
899 console.log(`Tags removed: ${logs.retag.removed}`);
900 console.log(`Categories deleted: ${logs.categoryDeleted.length}`);
901 console.log(`Delete skipped (still referenced): ${logs.categoryDeleteSkipped.length}`);
902 console.log(`Detailed log: ${logPath}`);
903}
904
905main().catch((error) => {
906 console.error('Consolidation failed:', error);
907 process.exit(1);
908});