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 }); console.log(`Loaded environment from ${envLocalPath}`); } else { dotenv.config(); console.log('No .env.local found, loaded default environment'); } 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'); process.exit(1); } const supabase = createClient(supabaseUrl, supabaseServiceKey, { auth: { persistSession: false, autoRefreshToken: false }, db: { schema: 'public' }, }); const TAG_DEFINITIONS = [ { name: 'Code Generation', icon: 'Code2', description: 'Tools and resources for generating, debugging, and refactoring code with AI.', keywords: ['code', 'coding', 'developer', 'programming', 'copilot', 'github', 'software', 'typescript', 'javascript', 'python', 'refactor', 'debug'], }, { name: 'Developer Tools', icon: 'Terminal', description: 'AI products for engineering productivity and software development workflows.', keywords: ['api', 'sdk', 'cli', 'developer', 'devops', 'repository', 'integration', 'automation'], }, { name: 'LLMs', icon: 'Brain', description: 'Large language model platforms, tooling, and educational resources.', keywords: ['llm', 'large language model', 'foundation model', 'transformer', 'gpt', 'claude', 'gemini', 'llama', 'mistral'], }, { name: 'Natural Language Processing', icon: 'Languages', description: 'AI for text understanding, language analysis, and semantic processing.', keywords: ['nlp', 'language understanding', 'text analysis', 'sentiment', 'entity extraction', 'classification', 'summarization'], }, { name: 'Prompt Engineering', icon: 'MessageSquareQuote', description: 'Techniques and tools for designing effective AI prompts and prompt workflows.', keywords: ['prompt', 'prompting', 'prompt engineering', 'system prompt', 'instruction tuning', 'few-shot'], }, { name: 'Chatbots', icon: 'MessageCircle', description: 'Conversational AI assistants, chatbot frameworks, and support tools.', keywords: ['chatbot', 'assistant', 'conversation', 'customer support', 'chat', 'agent'], }, { name: 'Agent Frameworks', icon: 'Bot', description: 'Frameworks and platforms for autonomous and multi-step AI agents.', keywords: ['agent framework', 'autonomous agent', 'tool use', 'orchestration', 'multi-agent', 'agentic'], }, { name: 'Image Generation', icon: 'Image', description: 'AI tools and resources for creating images, illustrations, and visual assets.', keywords: ['image generation', 'text to image', 'midjourney', 'stable diffusion', 'dall-e', 'illustration', 'photo', 'art'], }, { name: 'Computer Vision', icon: 'ScanEye', description: 'AI systems for visual understanding, object detection, and image analysis.', keywords: ['computer vision', 'object detection', 'segmentation', 'ocr', 'vision model', 'image recognition'], }, { name: 'Video Generation', icon: 'Clapperboard', description: 'AI for generating, editing, and transforming video content.', keywords: ['video generation', 'text to video', 'video editing', 'animation', 'sora', 'runway'], }, { name: 'Audio Generation', icon: 'Music2', description: 'AI tools for creating music, sound effects, and synthetic audio.', keywords: ['audio generation', 'music generation', 'sound design', 'voice clone', 'sound effects'], }, { name: 'Speech Recognition', icon: 'Mic', description: 'Speech-to-text and spoken language understanding systems.', keywords: ['speech recognition', 'speech-to-text', 'stt', 'transcribe', 'dictation', 'voice recognition'], }, { name: 'Text-to-Speech', icon: 'Volume2', description: 'Systems that synthesize natural speech from text.', keywords: ['text-to-speech', 'tts', 'speech synthesis', 'voice synthesis', 'narration'], }, { name: 'Data Science', icon: 'BarChart3', description: 'AI applications for data analysis, statistics, and analytical workflows.', keywords: ['data science', 'analytics', 'dashboard', 'statistics', 'data analysis', 'notebook'], }, { name: 'Machine Learning', icon: 'Cpu', description: 'Practical ML methods, tooling, model training, and deployment.', keywords: ['machine learning', 'ml', 'model training', 'feature engineering', 'prediction', 'classification'], }, { name: 'Deep Learning', icon: 'Network', description: 'Neural network architectures, training techniques, and DL applications.', keywords: ['deep learning', 'neural network', 'cnn', 'rnn', 'attention', 'backpropagation'], }, { name: 'MLOps', icon: 'Workflow', description: 'Infrastructure and lifecycle management for ML and AI models in production.', keywords: ['mlops', 'model deployment', 'monitoring', 'model registry', 'pipeline', 'serving'], }, { name: 'Workflow Automation', icon: 'GitBranch', description: 'AI-powered automation for repetitive and multi-step workflows.', keywords: ['workflow', 'automation', 'zapier', 'make.com', 'n8n', 'pipeline', 'automate'], }, { name: 'Search', icon: 'Search', description: 'Semantic, vector, and AI-assisted search technologies.', keywords: ['search', 'semantic search', 'vector search', 'retrieval', 'rag', 'indexing'], }, { name: 'Research', icon: 'FlaskConical', description: 'AI research platforms, methods, and academic learning resources.', keywords: ['research', 'paper', 'benchmark', 'evaluation', 'study', 'experiment'], }, { name: 'Writing Assistance', icon: 'PenSquare', description: 'AI writing assistants for drafting, editing, and content generation.', keywords: ['writing', 'copywriting', 'grammar', 'blog', 'content', 'draft', 'rewrite'], }, { name: 'Productivity', icon: 'Briefcase', description: 'AI tools that improve knowledge work and business productivity.', keywords: ['productivity', 'task management', 'notes', 'meeting', 'email', 'workflow'], }, { name: 'No-Code AI', icon: 'Puzzle', description: 'No-code and low-code AI builders for non-developer workflows.', keywords: ['no-code', 'low-code', 'drag and drop', 'builder', 'visual workflow'], }, { name: 'APIs', icon: 'Plug', description: 'API-first AI services, platforms, and integration layers.', keywords: ['api', 'endpoint', 'rest', 'webhook', 'integration', 'platform'], }, { name: 'Courses', icon: 'GraduationCap', description: 'Structured learning courses focused on AI topics and practical skills.', keywords: ['course', 'curriculum', 'bootcamp', 'class', 'certification'], }, { name: 'Tutorials', icon: 'BookOpen', description: 'Step-by-step tutorials and guides for building with AI.', keywords: ['tutorial', 'guide', 'how to', 'walkthrough', 'hands-on'], }, { name: 'Documentation', icon: 'FileText', description: 'Technical documentation, references, and implementation guides for AI products.', keywords: ['documentation', 'docs', 'reference', 'quickstart', 'manual'], }, { name: 'Ethics & Safety', icon: 'ShieldCheck', description: 'Responsible AI, alignment, safety engineering, and governance.', keywords: ['safety', 'ethics', 'alignment', 'responsible ai', 'risk', 'governance'], }, { name: 'Open Source', icon: 'Github', description: 'Open-source AI models, frameworks, and community resources.', keywords: ['open source', 'oss', 'github', 'gitlab', 'apache', 'mit license'], }, ]; const GENERIC_CATEGORY_NAMES = new Set([ 'general ai', 'general', 'other', 'misc', 'miscellaneous', 'ai', 'artificial intelligence', 'ai tools', 'all', 'uncategorized', ]); const TOOL_FALLBACK_TAGS = ['LLMs', 'Productivity', 'Workflow Automation']; const LEARNING_FALLBACK_TAGS = ['Machine Learning', 'Natural Language Processing', 'Prompt Engineering']; 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 isGenericCategory(name) { const n = normalize(name); if (!n) return true; if (GENERIC_CATEGORY_NAMES.has(n)) return true; if (n === 'general ai tools') return true; if (n.startsWith('general ')) return true; return false; } function containsKeyword(text, keyword) { const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); const regex = new RegExp(`(^|[^a-z0-9])${escaped}([^a-z0-9]|$)`, 'i'); return regex.test(text); } function inferTagScores({ name, description, url, kind }) { const text = `${name || ''} ${description || ''}`.toLowerCase(); const urlText = String(url || '').toLowerCase(); const scores = new Map(); for (const def of TAG_DEFINITIONS) { let score = 0; for (const keyword of def.keywords) { if (containsKeyword(text, keyword.toLowerCase())) { score += keyword.includes(' ') ? 3 : 2; } if (containsKeyword(urlText, keyword.toLowerCase())) { score += 1; } } if (def.name === 'Open Source' && (urlText.includes('github.com') || urlText.includes('gitlab.com'))) { score += 4; } if (def.name === 'Courses' && kind === 'learning') { if (containsKeyword(text, 'course') || containsKeyword(text, 'curriculum')) score += 3; } if (def.name === 'Tutorials' && kind === 'learning') { if (containsKeyword(text, 'tutorial') || containsKeyword(text, 'guide') || containsKeyword(text, 'walkthrough')) score += 3; } if (def.name === 'Documentation' && kind === 'learning') { if (containsKeyword(text, 'documentation') || containsKeyword(text, 'docs') || containsKeyword(text, 'reference')) score += 3; } if (score > 0) { scores.set(def.name, score); } } return Array.from(scores.entries()) .sort((a, b) => b[1] - a[1]) .map(([tag]) => tag); } async function fetchAllRows(table, columns) { const pageSize = 1000; let from = 0; const rows = []; 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 detectLearningTable() { const candidates = ['learning', 'learning_resources']; for (const table of candidates) { try { await fetchAllRows(table, 'id'); return table; } catch (error) { const message = error instanceof Error ? error.message : String(error); if (!message.includes('Could not find the table')) { throw error; } } } throw new Error('Could not find learning table: tried learning, learning_resources'); } async function detectLearningCategoryIdColumn() { const candidates = ['learning_id', 'learning_resource_id']; for (const col of candidates) { const { error } = await supabase.from('learning_categories').select(`${col}`).limit(1); if (!error) { return col; } if (!String(error.message || '').includes('column')) { throw new Error(`Unable to inspect learning_categories column ${col}: ${error.message}`); } } throw new Error('Could not find learning id column in learning_categories table'); } async function loadData() { const learningTable = await detectLearningTable(); const learningIdColumn = await detectLearningCategoryIdColumn(); const [categories, tools, learningResources, toolLinks, learningLinks] = await Promise.all([ fetchAllRows('categories', 'id, name, slug, icon, description'), fetchAllRows('tools', 'id, name, description, url'), fetchAllRows(learningTable, 'id, title, description, url'), fetchAllRows('tools_categories', 'tool_id, category_id, is_primary'), fetchAllRows('learning_categories', `${learningIdColumn}, category_id, is_primary`), ]); return { categories, tools, learningResources, toolLinks, learningLinks, learningTable, learningIdColumn }; } function buildCategoryIndexes(categories) { const byName = new Map(); const bySlug = new Map(); const byId = new Map(); for (const category of categories) { byName.set(normalize(category.name), category); bySlug.set(normalize(category.slug), category); byId.set(category.id, category); } return { byName, bySlug, byId }; } function uniqueName(items) { const seen = new Set(); return items.filter((v) => { const key = normalize(v); if (!key || seen.has(key)) return false; seen.add(key); return true; }); } async function ensureCategory(tagName, indexes, createdCategories) { const existing = indexes.byName.get(normalize(tagName)); if (existing) return existing; const def = TAG_DEFINITIONS.find((t) => t.name === tagName); const baseSlug = slugify(tagName); let slug = baseSlug; let counter = 2; while (indexes.bySlug.has(normalize(slug))) { slug = `${baseSlug}-${counter}`; counter += 1; } const payload = { name: tagName, slug, icon: def?.icon || 'Tag', description: def?.description || `Category for ${tagName}`, }; const { data, error } = await supabase .from('categories') .insert(payload) .select('id, name, slug, icon, description') .single(); if (error) { throw new Error(`Failed to create category "${tagName}": ${error.message}`); } indexes.byName.set(normalize(data.name), data); indexes.bySlug.set(normalize(data.slug), data); indexes.byId.set(data.id, data); createdCategories.push(data); console.log(`[create-category] ${data.name} (id=${data.id}, slug=${data.slug}, icon=${data.icon})`); return data; } function buildLinksByItem(links, itemKey) { const map = new Map(); for (const row of links) { const id = row[itemKey]; if (!map.has(id)) map.set(id, []); map.get(id).push(row); } return map; } function pickFinalTagNames({ currentCategoryNames, primaryCurrentName, inferredNames, kind }) { const currentSpecific = currentCategoryNames.filter((name) => !isGenericCategory(name)); const fallback = kind === 'tool' ? TOOL_FALLBACK_TAGS : LEARNING_FALLBACK_TAGS; const final = []; if (primaryCurrentName && !isGenericCategory(primaryCurrentName)) { final.push(primaryCurrentName); } for (const name of currentSpecific) { final.push(name); } if (final.length < 3) { for (const name of inferredNames) { final.push(name); if (uniqueName(final).length >= 3) break; } } if (uniqueName(final).length < 3) { for (const name of fallback) { final.push(name); if (uniqueName(final).length >= 3) break; } } let deduped = uniqueName(final); if (deduped.length < 3) { for (const name of TAG_DEFINITIONS.map((d) => d.name)) { deduped.push(name); deduped = uniqueName(deduped); if (deduped.length >= 3) break; } } if (deduped.length < 3) { throw new Error('Unable to generate at least 3 tags for item'); } if (deduped.length > 5) { const currentSpecificSet = new Set(currentSpecific.map(normalize)); const mustKeep = deduped.filter((name) => currentSpecificSet.has(normalize(name))); if (mustKeep.length > 5) { // Preserve all existing specific tags to avoid deleting valid tags. return mustKeep; } const extras = deduped.filter((name) => !currentSpecificSet.has(normalize(name))); deduped = [...mustKeep, ...extras].slice(0, 5); } return deduped; } function pickPrimaryTagName({ finalNames, inferredNames, currentPrimaryName }) { if (currentPrimaryName && finalNames.some((n) => normalize(n) === normalize(currentPrimaryName))) { return finalNames.find((n) => normalize(n) === normalize(currentPrimaryName)); } for (const inferred of inferredNames) { const found = finalNames.find((n) => normalize(n) === normalize(inferred)); if (found) return found; } return finalNames[0]; } async function reconcileItem({ kind, item, itemName, itemDescription, itemUrl, itemIdKey, junctionTable, linkRows, indexes, createdCategories, summary, }) { const currentCategoryRows = linkRows.map((row) => { const category = indexes.byId.get(row.category_id); return { categoryId: row.category_id, categoryName: category?.name || `Unknown(${row.category_id})`, isPrimary: !!row.is_primary, }; }); const currentCategoryNames = currentCategoryRows.map((row) => row.categoryName); const currentPrimary = currentCategoryRows.find((row) => row.isPrimary); const currentPrimaryName = currentPrimary?.categoryName; const inferredNames = inferTagScores({ name: itemName, description: itemDescription, url: itemUrl, kind: kind === 'tool' ? 'tool' : 'learning', }); const finalTagNames = pickFinalTagNames({ currentCategoryNames, primaryCurrentName: currentPrimaryName, inferredNames, kind, }); const primaryTagName = pickPrimaryTagName({ finalNames: finalTagNames, inferredNames, currentPrimaryName, }); const finalCategories = []; for (const tagName of finalTagNames) { const category = await ensureCategory(tagName, indexes, createdCategories); finalCategories.push(category); } const finalCategoryIds = new Set(finalCategories.map((c) => c.id)); const currentCategoryIds = new Set(currentCategoryRows.map((c) => c.categoryId)); const toAdd = finalCategories.filter((cat) => !currentCategoryIds.has(cat.id)); const removableGenericIds = currentCategoryRows .filter((row) => isGenericCategory(row.categoryName)) .map((row) => row.categoryId) .filter((id) => !finalCategoryIds.has(id)); const removeIds = Array.from(new Set(removableGenericIds)); if (toAdd.length > 0) { const payload = toAdd.map((cat) => ({ [itemIdKey]: item.id, category_id: cat.id, is_primary: false, })); const { error } = await supabase.from(junctionTable).insert(payload); if (error) { throw new Error(`Failed adding ${kind} categories for ${item.id}: ${error.message}`); } } if (removeIds.length > 0) { const { error } = await supabase .from(junctionTable) .delete() .eq(itemIdKey, item.id) .in('category_id', removeIds); if (error) { throw new Error(`Failed removing generic ${kind} categories for ${item.id}: ${error.message}`); } } const primaryCategory = finalCategories.find((c) => normalize(c.name) === normalize(primaryTagName)); if (!primaryCategory) { throw new Error(`Primary category not found for ${kind} ${item.id}`); } const { error: clearPrimaryError } = await supabase .from(junctionTable) .update({ is_primary: false }) .eq(itemIdKey, item.id); if (clearPrimaryError) { throw new Error(`Failed clearing primary on ${kind} ${item.id}: ${clearPrimaryError.message}`); } const { error: setPrimaryError } = await supabase .from(junctionTable) .update({ is_primary: true }) .eq(itemIdKey, item.id) .eq('category_id', primaryCategory.id); if (setPrimaryError) { throw new Error(`Failed setting primary on ${kind} ${item.id}: ${setPrimaryError.message}`); } const beforeSpecificCount = currentCategoryRows.filter((row) => !isGenericCategory(row.categoryName)).length; const changed = toAdd.length > 0 || removeIds.length > 0 || !currentPrimary || normalize(currentPrimary.categoryName) !== normalize(primaryCategory.name) || beforeSpecificCount < 3; if (changed) { summary.changedItems += 1; summary.addedLinks += toAdd.length; summary.removedLinks += removeIds.length; summary.primaryUpdates += 1; const removedNames = removeIds .map((id) => indexes.byId.get(id)?.name) .filter(Boolean); const finalNames = finalCategories.map((c) => c.name); console.log( `[update-${kind}] id=${item.id} name="${itemName}" add=[${toAdd.map((c) => c.name).join(', ')}] remove=[${removedNames.join(', ')}] primary="${primaryCategory.name}" final=[${finalNames.join(', ')}]` ); } if (finalCategories.length < 3) { summary.lowTagItems.push({ kind, id: item.id, name: itemName, count: finalCategories.length }); } if (finalCategories.length > 5) { summary.highTagItems.push({ kind, id: item.id, name: itemName, count: finalCategories.length }); } } async function auditAndFixTags() { console.log('Starting audit and tag-fix for tools and learning resources...'); const { categories, tools, learningResources, toolLinks, learningLinks, learningTable, learningIdColumn } = await loadData(); const indexes = buildCategoryIndexes(categories); const createdCategories = []; console.log( `Loaded ${categories.length} categories, ${tools.length} tools, ${learningResources.length} learning resources from ${learningTable}, ${toolLinks.length} tool links, ${learningLinks.length} learning links (id column: ${learningIdColumn}).` ); const toolLinksByToolId = buildLinksByItem(toolLinks, 'tool_id'); const learningLinksByLearningId = buildLinksByItem(learningLinks, learningIdColumn); const summary = { changedItems: 0, addedLinks: 0, removedLinks: 0, primaryUpdates: 0, lowTagItems: [], highTagItems: [], }; for (const tool of tools) { await reconcileItem({ kind: 'tool', item: tool, itemName: tool.name || `Tool ${tool.id}`, itemDescription: tool.description || '', itemUrl: tool.url || '', itemIdKey: 'tool_id', junctionTable: 'tools_categories', linkRows: toolLinksByToolId.get(tool.id) || [], indexes, createdCategories, summary, }); } for (const learning of learningResources) { await reconcileItem({ kind: 'learning', item: learning, itemName: learning.title || `Learning ${learning.id}`, itemDescription: learning.description || '', itemUrl: learning.url || '', itemIdKey: learningIdColumn, junctionTable: 'learning_categories', linkRows: learningLinksByLearningId.get(learning.id) || [], indexes, createdCategories, summary, }); } console.log('--- Summary ---'); console.log(`Created categories: ${createdCategories.length}`); console.log(`Changed items: ${summary.changedItems}`); console.log(`Added links: ${summary.addedLinks}`); console.log(`Removed generic links: ${summary.removedLinks}`); console.log(`Primary updates: ${summary.primaryUpdates}`); if (summary.lowTagItems.length > 0) { console.log(`Items under 3 tags: ${summary.lowTagItems.length}`); for (const item of summary.lowTagItems.slice(0, 25)) { console.log(` - [${item.kind}] id=${item.id} name="${item.name}" count=${item.count}`); } } if (summary.highTagItems.length > 0) { console.log(`Items over 5 tags (preserved existing specific tags): ${summary.highTagItems.length}`); for (const item of summary.highTagItems.slice(0, 25)) { console.log(` - [${item.kind}] id=${item.id} name="${item.name}" count=${item.count}`); } } console.log('Audit complete.'); } await auditAndFixTags();