import { createClient } from '@supabase/supabase-js'; import dotenv from 'dotenv'; import fs from 'fs'; import path from 'path'; const envLocalPath = path.resolve(process.cwd(), '.env.local'); if (fs.existsSync(envLocalPath)) { dotenv.config({ path: envLocalPath }); } else { dotenv.config(); } const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !supabaseServiceKey) { console.error('Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env.local'); process.exit(1); } const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { persistSession: false, autoRefreshToken: false }, db: { schema: 'public' }, }); const GENERIC_DELETE_NAMES = new Set([ 'general ai', 'ai', 'artificial intelligence', 'ai tools', 'general', 'other', 'misc', 'miscellaneous', 'uncategorized', ]); const EXPLICIT_MERGE_RULES = [ { canonical: 'Code Generation', aliases: ['code generation', 'code assistant', 'coding tools'] }, { canonical: 'Developer Tools', aliases: ['dev tools', 'developer tools', 'development tools'] }, { canonical: 'Data Science', aliases: ['data analysis', 'data science'] }, { canonical: 'Natural Language Processing', aliases: ['nlp', 'natural language processing'] }, { canonical: 'Machine Learning', aliases: ['ml', 'machine learning'] }, { canonical: 'Deep Learning', aliases: ['dl', 'deep learning'] }, { canonical: 'Courses', aliases: ['course', 'courses'] }, { canonical: 'Tutorials', aliases: ['tutorial', 'tutorials'] }, ]; const COLLECTION_PLURAL_BASES = new Set([ 'course', 'tutorial', 'chatbot', 'agent', 'api', 'tool', 'framework', 'model', 'resource', 'dataset', 'plugin', 'extension', ]); const INFERENCE_KEYWORDS = { 'code generation': ['code', 'coding', 'programming', 'copilot', 'cursor', 'refactor', 'debug'], 'developer tools': ['sdk', 'cli', 'developer', 'devops', 'integration', 'api'], 'data science': ['data science', 'analytics', 'analysis', 'statistics', 'dashboard', 'notebook'], 'natural language processing': ['nlp', 'language processing', 'text analysis', 'sentiment', 'entity extraction', 'semantic'], 'machine learning': ['machine learning', 'ml', 'model training', 'classification', 'regression', 'prediction'], 'deep learning': ['deep learning', 'neural network', 'transformer', 'cnn', 'rnn'], 'courses': ['course', 'curriculum', 'class', 'bootcamp', 'certification'], 'tutorials': ['tutorial', 'guide', 'walkthrough', 'how to', 'step by step'], 'documentation': ['documentation', 'docs', 'reference', 'manual', 'quickstart'], 'chatbots': ['chatbot', 'assistant', 'conversation', 'conversational'], 'prompt engineering': ['prompt', 'system prompt', 'few-shot', 'instruction'], 'image generation': ['image generation', 'text to image', 'midjourney', 'stable diffusion', 'dall-e'], 'video generation': ['video generation', 'text to video', 'sora', 'runway'], 'audio generation': ['audio generation', 'music generation', 'voice generation', 'sound design'], 'speech recognition': ['speech recognition', 'speech to text', 'stt', 'transcription', 'asr'], 'text-to-speech': ['text to speech', 'tts', 'speech synthesis', 'voice synthesis'], 'workflow automation': ['workflow', 'automation', 'zapier', 'n8n', 'make.com', 'pipeline'], search: ['search', 'retrieval', 'rag', 'semantic search', 'vector search'], research: ['research', 'paper', 'arxiv', 'benchmark', 'study', 'evaluation'], apis: ['api', 'endpoint', 'webhook', 'rest api'], 'open source': ['open source', 'github', 'gitlab', 'oss'], 'computer vision': ['computer vision', 'image recognition', 'object detection', 'segmentation', 'ocr'], }; const FALLBACK_BY_KIND = { tools: ['Developer Tools', 'Code Generation', 'Machine Learning'], news: ['Machine Learning', 'Data Science', 'Natural Language Processing'], posts: ['Tutorials', 'Documentation', 'Machine Learning'], learning: ['Courses', 'Tutorials', 'Machine Learning'], }; const CONTENT_CANDIDATES = [ { kind: 'tools', itemTableCandidates: ['tools'], junctionTableCandidates: ['tools_categories'], itemIdColumnCandidates: ['tool_id'], textColumnCandidates: ['description', 'content'], nameColumnCandidates: ['name', 'title'], }, { kind: 'news', itemTableCandidates: ['news', 'news_stories'], junctionTableCandidates: ['news_categories'], itemIdColumnCandidates: ['news_id', 'news_story_id'], textColumnCandidates: ['content', 'description'], nameColumnCandidates: ['title', 'name'], }, { kind: 'posts', itemTableCandidates: ['posts', 'blog_posts'], junctionTableCandidates: ['posts_categories', 'post_categories', 'blog_posts_categories'], itemIdColumnCandidates: ['post_id', 'blog_post_id', 'posts_id'], textColumnCandidates: ['content', 'description', 'summary'], nameColumnCandidates: ['title', 'name'], }, { kind: 'learning', itemTableCandidates: ['learning', 'learning_resources'], junctionTableCandidates: ['learning_categories', 'learning_resources_categories'], itemIdColumnCandidates: ['learning_id', 'learning_resource_id'], textColumnCandidates: ['description', 'content', 'summary'], nameColumnCandidates: ['title', 'name'], }, ]; function normalize(value) { return String(value || '').trim().toLowerCase(); } function slugify(value) { return String(value || '') .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/(^-|-$)+/g, '') .slice(0, 80); } function isMissingRelationError(error) { const msg = normalize(error?.message || ''); return ( msg.includes('does not exist') || msg.includes('could not find the table') || msg.includes('schema cache') || msg.includes('relation') ); } function isMissingColumnError(error) { const msg = normalize(error?.message || ''); return msg.includes('column') || msg.includes('schema cache'); } function isDuplicateError(error) { const msg = normalize(error?.message || ''); return msg.includes('duplicate key') || msg.includes('unique constraint'); } async function fetchAllRows(table, columns) { const pageSize = 1000; const rows = []; let from = 0; while (true) { const to = from + pageSize - 1; const { data, error } = await supabase.from(table).select(columns).range(from, to); if (error) throw new Error(`Failed to fetch ${table}: ${error.message}`); if (!data || data.length === 0) break; rows.push(...data); if (data.length < pageSize) break; from += pageSize; } return rows; } async function detectTable(candidates) { for (const table of candidates) { const { error } = await supabase.from(table).select('id').limit(1); if (!error) return table; if (isMissingRelationError(error)) continue; throw new Error(`Unexpected error detecting table ${table}: ${error.message}`); } return null; } async function detectColumn(table, candidates) { for (const col of candidates) { const { error } = await supabase.from(table).select(col).limit(1); if (!error) return col; if (isMissingColumnError(error)) continue; throw new Error(`Unexpected error detecting column ${table}.${col}: ${error.message}`); } return null; } async function detectExistingColumns(table, candidates) { const found = []; for (const col of candidates) { const { error } = await supabase.from(table).select(col).limit(1); if (!error) { found.push(col); continue; } if (isMissingColumnError(error)) continue; throw new Error(`Unexpected error detecting column ${table}.${col}: ${error.message}`); } return found; } function pickBestCanonical(categories) { const scored = [...categories].sort((a, b) => { const aName = String(a.name || ''); const bName = String(b.name || ''); const aLower = normalize(aName); const bLower = normalize(bName); const aScore = (aName === aName.toUpperCase() ? -1 : 0) + aName.length + aName.split(/\s+/).length; const bScore = (bName === bName.toUpperCase() ? -1 : 0) + bName.length + bName.split(/\s+/).length; if (aScore !== bScore) return bScore - aScore; if (aLower !== bLower) return aLower.localeCompare(bLower); return Number(a.id) - Number(b.id); }); return scored[0]; } function singularBase(name) { const n = normalize(name); if (!n || n.includes(' ')) return null; if (n.endsWith('ies') && n.length > 3) return `${n.slice(0, -3)}y`; if (n.endsWith('s') && !n.endsWith('ss') && n.length > 2) return n.slice(0, -1); return n; } function scoreCategory(category, text) { const name = normalize(category.name); const slug = normalize(category.slug || ''); const textLower = text; let score = 0; if (name && textLower.includes(name)) score += 8; const nameTokens = name.split(/[^a-z0-9]+/).filter((t) => t.length > 2); for (const token of nameTokens) { if (textLower.includes(token)) score += 1; } const slugTokens = slug.split(/[^a-z0-9]+/).filter((t) => t.length > 2); for (const token of slugTokens) { if (textLower.includes(token)) score += 1; } const keywordList = INFERENCE_KEYWORDS[name] || []; for (const keyword of keywordList) { if (textLower.includes(normalize(keyword))) score += keyword.includes(' ') ? 4 : 2; } return score; } function uniqueByNormalize(names) { const seen = new Set(); const output = []; for (const name of names) { const key = normalize(name); if (!key || seen.has(key)) continue; seen.add(key); output.push(name); } return output; } async function detectSchema() { const schemas = []; for (const candidate of CONTENT_CANDIDATES) { const itemTable = await detectTable(candidate.itemTableCandidates); const junctionTable = await detectTable(candidate.junctionTableCandidates); if (!itemTable || !junctionTable) continue; const itemIdColumn = await detectColumn(junctionTable, candidate.itemIdColumnCandidates); if (!itemIdColumn) continue; const nameColumn = await detectColumn(itemTable, candidate.nameColumnCandidates); if (!nameColumn) continue; const textColumns = await detectExistingColumns(itemTable, candidate.textColumnCandidates); const hasPrimaryCategoryId = !!(await detectColumn(itemTable, ['primary_category_id'])); schemas.push({ kind: candidate.kind, itemTable, junctionTable, itemIdColumn, nameColumn, textColumns, hasPrimaryCategoryId, }); } return schemas; } function buildCategoryState(categories) { const byId = new Map(); const byName = new Map(); const bySlug = new Map(); for (const category of categories) { byId.set(category.id, category); const key = normalize(category.name); if (!byName.has(key)) byName.set(key, []); byName.get(key).push(category); bySlug.set(normalize(category.slug || ''), category); } return { byId, byName, bySlug, categories }; } async function ensureCategory(name, state, logs) { const key = normalize(name); const existing = state.byName.get(key); if (existing && existing.length > 0) { return pickBestCanonical(existing); } const baseSlug = slugify(name); let slug = baseSlug; let counter = 2; while (state.bySlug.has(normalize(slug))) { slug = `${baseSlug}-${counter}`; counter += 1; } const payload = { name, slug, icon: 'Tag', description: `${name} resources and content`, }; const { data, error } = await supabase .from('categories') .insert(payload) .select('id, name, slug, icon, description') .single(); if (error) { throw new Error(`Failed to create canonical category ${name}: ${error.message}`); } state.categories.push(data); state.byId.set(data.id, data); state.bySlug.set(normalize(data.slug), data); state.byName.set(key, [data]); logs.createdCategories.push({ id: data.id, name: data.name, slug: data.slug }); return data; } function addMergeMapping(mappings, fromCategory, toCategory, reason) { if (!fromCategory) return; if (toCategory && fromCategory.id === toCategory.id) return; const existing = mappings.get(fromCategory.id); if (existing) { if (existing.toId === null) return; if (toCategory && existing.toId !== toCategory.id) { return; } } mappings.set(fromCategory.id, { fromId: fromCategory.id, fromName: fromCategory.name, toId: toCategory ? toCategory.id : null, toName: toCategory ? toCategory.name : null, reason, }); } async function buildMergePlan(state, logs) { const mappings = new Map(); for (const category of state.categories) { const n = normalize(category.name); if (GENERIC_DELETE_NAMES.has(n)) { addMergeMapping(mappings, category, null, 'generic category deletion list'); } } for (const [nameKey, categories] of state.byName.entries()) { if (categories.length < 2) continue; if (GENERIC_DELETE_NAMES.has(nameKey)) { for (const category of categories) addMergeMapping(mappings, category, null, 'generic duplicate deletion'); continue; } const canonical = pickBestCanonical(categories); for (const category of categories) { if (category.id !== canonical.id) { addMergeMapping(mappings, category, canonical, 'exact duplicate name (case/format variant)'); } } } for (const rule of EXPLICIT_MERGE_RULES) { const canonical = await ensureCategory(rule.canonical, state, logs); const aliasSet = new Set(rule.aliases.map((a) => normalize(a))); for (const category of state.categories) { const n = normalize(category.name); if (!aliasSet.has(n)) continue; if (n === normalize(canonical.name) && category.id === canonical.id) continue; addMergeMapping(mappings, category, canonical, `synonym/variant rule -> ${rule.canonical}`); } } const byBase = new Map(); for (const category of state.categories) { const base = singularBase(category.name); if (!base || !COLLECTION_PLURAL_BASES.has(base)) continue; if (!byBase.has(base)) byBase.set(base, []); byBase.get(base).push(category); } for (const [base, categories] of byBase.entries()) { if (categories.length < 2) continue; const pluralName = `${base}s`; const canonical = categories.find((c) => normalize(c.name) === pluralName) || categories.find((c) => normalize(c.name) === `${base}ies`) || pickBestCanonical(categories); for (const category of categories) { if (category.id === canonical.id) continue; addMergeMapping(mappings, category, canonical, `obvious singular/plural duplicate (${base})`); } } return [...mappings.values()]; } async function safeInsertLink(junctionTable, itemIdColumn, itemId, categoryId, isPrimary) { const { data: existing, error: checkError } = await supabase .from(junctionTable) .select(`${itemIdColumn}, category_id, is_primary`) .eq(itemIdColumn, itemId) .eq('category_id', categoryId) .limit(1); if (checkError) throw new Error(`Failed checking existing link ${junctionTable}: ${checkError.message}`); if (existing && existing.length > 0) { if (isPrimary && !existing[0].is_primary) { const { error: updateError } = await supabase .from(junctionTable) .update({ is_primary: true }) .eq(itemIdColumn, itemId) .eq('category_id', categoryId); if (updateError) throw new Error(`Failed promoting existing link to primary in ${junctionTable}: ${updateError.message}`); } return false; } const { error: insertError } = await supabase .from(junctionTable) .insert({ [itemIdColumn]: itemId, category_id: categoryId, is_primary: !!isPrimary }); if (insertError) { if (isDuplicateError(insertError)) return false; throw new Error(`Failed inserting link into ${junctionTable}: ${insertError.message}`); } return true; } async function moveJunctionLinks(schema, fromId, toId, logs) { const rows = await fetchAllRows(schema.junctionTable, `${schema.itemIdColumn}, category_id, is_primary`); const impacted = rows.filter((row) => row.category_id === fromId); if (impacted.length === 0) return; for (const row of impacted) { const itemId = row[schema.itemIdColumn]; if (toId !== null) { const inserted = await safeInsertLink(schema.junctionTable, schema.itemIdColumn, itemId, toId, !!row.is_primary); if (inserted) logs.movedLinks += 1; else logs.skippedDuplicateLinks += 1; } const { error: deleteError } = await supabase .from(schema.junctionTable) .delete() .eq(schema.itemIdColumn, itemId) .eq('category_id', fromId); if (deleteError) { throw new Error(`Failed deleting old link from ${schema.junctionTable}: ${deleteError.message}`); } logs.deletedLinks += 1; } } async function updatePrimaryCategoryColumn(schema, fromId, toId, logs) { if (!schema.hasPrimaryCategoryId) return; if (toId === null) { const { error } = await supabase .from(schema.itemTable) .update({ primary_category_id: null }) .eq('primary_category_id', fromId); if (error) throw new Error(`Failed nulling ${schema.itemTable}.primary_category_id from ${fromId}: ${error.message}`); logs.primaryCategoryUpdates += 1; return; } const { error } = await supabase .from(schema.itemTable) .update({ primary_category_id: toId }) .eq('primary_category_id', fromId); if (error) throw new Error(`Failed updating ${schema.itemTable}.primary_category_id from ${fromId} to ${toId}: ${error.message}`); logs.primaryCategoryUpdates += 1; } function buildItemsById(rows) { const map = new Map(); for (const row of rows) map.set(row.id, row); return map; } function buildLinksByItem(links, itemIdColumn) { const map = new Map(); for (const row of links) { const itemId = row[itemIdColumn]; if (!map.has(itemId)) map.set(itemId, []); map.get(itemId).push(row); } return map; } function getItemText(item, schema) { const headline = String(item[schema.nameColumn] || ''); const body = schema.textColumns.map((col) => String(item[col] || '')).join('\n'); return `${headline}\n${body}`.toLowerCase().slice(0, 40000); } function inferCategoryCandidates({ item, schema, availableCategories }) { const text = getItemText(item, schema); const scored = []; for (const category of availableCategories) { const score = scoreCategory(category, text); if (score > 0) scored.push({ category, score }); } scored.sort((a, b) => b.score - a.score || Number(a.category.id) - Number(b.category.id)); return scored.map((entry) => entry.category.id); } async function ensureFallbackCategories(state, logs) { const needed = uniqueByNormalize(Object.values(FALLBACK_BY_KIND).flat()); for (const name of needed) { await ensureCategory(name, state, logs); } } async function reconcileItemTags({ item, schema, linkRows, state, genericDeleteIds, logs }) { const currentRows = linkRows || []; const itemId = item.id; const dedupCurrent = []; const seenCurrent = new Set(); for (const row of currentRows) { const key = `${row[schema.itemIdColumn]}::${row.category_id}`; if (seenCurrent.has(key)) continue; seenCurrent.add(key); dedupCurrent.push(row); } const currentPrimaryRow = dedupCurrent.find((r) => !!r.is_primary); const currentPrimaryId = currentPrimaryRow?.category_id || null; const currentSpecificIds = dedupCurrent .map((r) => r.category_id) .filter((id) => !genericDeleteIds.has(id) && state.byId.has(id)); const availableCategories = state.categories.filter((c) => !genericDeleteIds.has(c.id)); const inferredIds = inferCategoryCandidates({ item, schema, availableCategories }); const finalIds = []; const addFinal = (id) => { if (!id) return; if (finalIds.includes(id)) return; if (!state.byId.has(id)) return; if (genericDeleteIds.has(id)) return; if (finalIds.length >= 5) return; finalIds.push(id); }; if (currentPrimaryId) addFinal(currentPrimaryId); for (const id of currentSpecificIds) addFinal(id); for (const id of inferredIds) { addFinal(id); if (finalIds.length >= 5) break; } if (finalIds.length < 3) { const fallbackNames = FALLBACK_BY_KIND[schema.kind] || []; for (const fallbackName of fallbackNames) { const options = state.byName.get(normalize(fallbackName)) || []; const cat = options[0]; if (!cat) continue; addFinal(cat.id); if (finalIds.length >= 3) break; } } if (finalIds.length < 3) { for (const category of availableCategories) { addFinal(category.id); if (finalIds.length >= 3) break; } } if (finalIds.length > 5) { finalIds.length = 5; } if (finalIds.length < 3) { throw new Error(`Unable to assign at least 3 tags for ${schema.kind} id=${itemId}`); } let primaryId = null; if (currentPrimaryId && finalIds.includes(currentPrimaryId)) { primaryId = currentPrimaryId; } else { primaryId = inferredIds.find((id) => finalIds.includes(id)) || finalIds[0]; } const finalSet = new Set(finalIds); const currentSet = new Set(dedupCurrent.map((r) => r.category_id)); const toDelete = [...currentSet].filter((id) => !finalSet.has(id)); const toAdd = [...finalSet].filter((id) => !currentSet.has(id)); if (toDelete.length > 0) { const { error } = await supabase .from(schema.junctionTable) .delete() .eq(schema.itemIdColumn, itemId) .in('category_id', toDelete); if (error) throw new Error(`Failed deleting old tags for ${schema.kind} id=${itemId}: ${error.message}`); logs.retag.removed += toDelete.length; } for (const categoryId of toAdd) { const inserted = await safeInsertLink(schema.junctionTable, schema.itemIdColumn, itemId, categoryId, false); if (inserted) logs.retag.added += 1; } const { error: clearPrimaryError } = await supabase .from(schema.junctionTable) .update({ is_primary: false }) .eq(schema.itemIdColumn, itemId); if (clearPrimaryError) { throw new Error(`Failed clearing primary flags for ${schema.kind} id=${itemId}: ${clearPrimaryError.message}`); } const { error: setPrimaryError } = await supabase .from(schema.junctionTable) .update({ is_primary: true }) .eq(schema.itemIdColumn, itemId) .eq('category_id', primaryId); if (setPrimaryError) { throw new Error(`Failed setting primary tag for ${schema.kind} id=${itemId}: ${setPrimaryError.message}`); } if (schema.hasPrimaryCategoryId) { const { error: primaryUpdateError } = await supabase .from(schema.itemTable) .update({ primary_category_id: primaryId }) .eq('id', itemId); if (primaryUpdateError) { throw new Error(`Failed updating ${schema.itemTable}.primary_category_id for id=${itemId}: ${primaryUpdateError.message}`); } } const oldSorted = [...currentSet].sort((a, b) => a - b); const newSorted = [...finalSet].sort((a, b) => a - b); const changed = oldSorted.length !== newSorted.length || oldSorted.some((value, index) => value !== newSorted[index]) || currentPrimaryId !== primaryId; if (changed) { logs.retag.itemsUpdated += 1; logs.retag.details.push({ kind: schema.kind, itemId, itemLabel: item[schema.nameColumn], oldCategoryIds: oldSorted, newCategoryIds: newSorted, oldPrimary: currentPrimaryId, newPrimary: primaryId, }); } } async function deleteCategoryIfUnreferenced(categoryId, categoryName, schemas, logs) { for (const schema of schemas) { const { data, error } = await supabase .from(schema.junctionTable) .select('category_id') .eq('category_id', categoryId) .limit(1); if (error) throw new Error(`Failed checking references in ${schema.junctionTable}: ${error.message}`); if (data && data.length > 0) { logs.categoryDeleteSkipped.push({ id: categoryId, name: categoryName, reason: `still referenced in ${schema.junctionTable}` }); return; } } for (const schema of schemas) { if (!schema.hasPrimaryCategoryId) continue; const { error } = await supabase .from(schema.itemTable) .update({ primary_category_id: null }) .eq('primary_category_id', categoryId); if (error) { throw new Error(`Failed nulling ${schema.itemTable}.primary_category_id for ${categoryId}: ${error.message}`); } } const { error: deleteError } = await supabase.from('categories').delete().eq('id', categoryId); if (deleteError) throw new Error(`Failed deleting category id=${categoryId} (${categoryName}): ${deleteError.message}`); logs.categoryDeleted.push({ id: categoryId, name: categoryName }); } async function main() { const startedAt = new Date().toISOString(); const logs = { startedAt, schema: [], createdCategories: [], mergePlan: [], movedLinks: 0, deletedLinks: 0, skippedDuplicateLinks: 0, primaryCategoryUpdates: 0, retag: { itemsUpdated: 0, added: 0, removed: 0, details: [], }, categoryDeleted: [], categoryDeleteSkipped: [], }; console.log('Detecting schema...'); const schemas = await detectSchema(); if (schemas.length === 0) { throw new Error('No compatible content/junction tables detected.'); } logs.schema = schemas.map((s) => ({ kind: s.kind, itemTable: s.itemTable, junctionTable: s.junctionTable, itemIdColumn: s.itemIdColumn, nameColumn: s.nameColumn, textColumns: s.textColumns, hasPrimaryCategoryId: s.hasPrimaryCategoryId, })); for (const s of logs.schema) { console.log(`- ${s.kind}: items=${s.itemTable}, junction=${s.junctionTable}, itemIdCol=${s.itemIdColumn}`); } const categories = await fetchAllRows('categories', 'id, name, slug, icon, description'); const state = buildCategoryState(categories); console.log(`Loaded ${categories.length} categories.`); await ensureFallbackCategories(state, logs); const mergePlan = await buildMergePlan(state, logs); logs.mergePlan = mergePlan; const mergeOperations = mergePlan.filter((m) => m.toId !== null); const genericDeleteIds = new Set( mergePlan .filter((m) => m.toId === null) .map((m) => m.fromId), ); console.log(`Merge operations: ${mergeOperations.length}`); console.log(`Generic/delete operations: ${genericDeleteIds.size}`); for (const op of mergeOperations) { for (const schema of schemas) { await moveJunctionLinks(schema, op.fromId, op.toId, logs); await updatePrimaryCategoryColumn(schema, op.fromId, op.toId, logs); } await deleteCategoryIfUnreferenced(op.fromId, op.fromName, schemas, logs); } const categoriesAfterMerges = await fetchAllRows('categories', 'id, name, slug, icon, description'); const refreshedState = buildCategoryState(categoriesAfterMerges); console.log('Re-auditing all content tags to enforce 3-5 tags and single primary...'); for (const schema of schemas) { const itemFields = ['id', schema.nameColumn, ...schema.textColumns, schema.hasPrimaryCategoryId ? 'primary_category_id' : null] .filter(Boolean) .join(', '); const items = await fetchAllRows(schema.itemTable, itemFields); const links = await fetchAllRows(schema.junctionTable, `${schema.itemIdColumn}, category_id, is_primary`); const itemsById = buildItemsById(items); const linksByItem = buildLinksByItem(links, schema.itemIdColumn); for (const [itemId, item] of itemsById.entries()) { const itemLinks = linksByItem.get(itemId) || []; await reconcileItemTags({ item, schema, linkRows: itemLinks, state: refreshedState, genericDeleteIds, logs, }); } console.log(`- Retagged ${schema.kind}: processed ${items.length} items`); } console.log('Deleting generic/useless categories after retagging...'); for (const categoryId of genericDeleteIds) { const category = refreshedState.byId.get(categoryId); if (!category) continue; for (const schema of schemas) { const { error } = await supabase .from(schema.junctionTable) .delete() .eq('category_id', categoryId); if (error) throw new Error(`Failed removing residual generic links from ${schema.junctionTable}: ${error.message}`); if (schema.hasPrimaryCategoryId) { const { error: primaryError } = await supabase .from(schema.itemTable) .update({ primary_category_id: null }) .eq('primary_category_id', categoryId); if (primaryError) throw new Error(`Failed nulling residual primary_category_id in ${schema.itemTable}: ${primaryError.message}`); } } await deleteCategoryIfUnreferenced(categoryId, category.name, schemas, logs); } const finishedAt = new Date().toISOString(); logs.finishedAt = finishedAt; const fileStamp = finishedAt.replace(/[:.]/g, '-'); const logPath = path.resolve(process.cwd(), 'logs', `consolidate-tags-${fileStamp}.json`); fs.mkdirSync(path.dirname(logPath), { recursive: true }); fs.writeFileSync(logPath, JSON.stringify(logs, null, 2)); console.log('Consolidation complete.'); console.log(`Created categories: ${logs.createdCategories.length}`); console.log(`Merged/deleted categories planned: ${logs.mergePlan.length}`); console.log(`Moved links: ${logs.movedLinks}`); console.log(`Deleted old links: ${logs.deletedLinks}`); console.log(`Skipped duplicate links: ${logs.skippedDuplicateLinks}`); console.log(`Items retagged: ${logs.retag.itemsUpdated}`); console.log(`Tags added: ${logs.retag.added}`); console.log(`Tags removed: ${logs.retag.removed}`); console.log(`Categories deleted: ${logs.categoryDeleted.length}`); console.log(`Delete skipped (still referenced): ${logs.categoryDeleteSkipped.length}`); console.log(`Detailed log: ${logPath}`); } main().catch((error) => { console.error('Consolidation failed:', error); process.exit(1); });