AI Resource Pro / website / scripts / audit-tags-tools-learning.mjs
| 1 | import { createClient } from '@supabase/supabase-js'; |
| 2 | import dotenv from 'dotenv'; |
| 3 | import fs from 'fs'; |
| 4 | import path from 'path'; |
| 5 | |
| 6 | const envLocalPath = path.resolve(process.cwd(), '.env.local'); |
| 7 | if (fs.existsSync(envLocalPath)) { |
| 8 | dotenv.config({ path: envLocalPath }); |
| 9 | console.log(`Loaded environment from ${envLocalPath}`); |
| 10 | } else { |
| 11 | dotenv.config(); |
| 12 | console.log('No .env.local found, loaded default environment'); |
| 13 | } |
| 14 | |
| 15 | const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; |
| 16 | const supabaseServiceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; |
| 17 | |
| 18 | if (!supabaseUrl || !supabaseServiceKey) { |
| 19 | console.error('Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY'); |
| 20 | process.exit(1); |
| 21 | } |
| 22 | |
| 23 | const supabase = createClient(supabaseUrl, supabaseServiceKey, { |
| 24 | auth: { persistSession: false, autoRefreshToken: false }, |
| 25 | db: { schema: 'public' }, |
| 26 | }); |
| 27 | |
| 28 | const TAG_DEFINITIONS = [ |
| 29 | { |
| 30 | name: 'Code Generation', |
| 31 | icon: 'Code2', |
| 32 | description: 'Tools and resources for generating, debugging, and refactoring code with AI.', |
| 33 | keywords: ['code', 'coding', 'developer', 'programming', 'copilot', 'github', 'software', 'typescript', 'javascript', 'python', 'refactor', 'debug'], |
| 34 | }, |
| 35 | { |
| 36 | name: 'Developer Tools', |
| 37 | icon: 'Terminal', |
| 38 | description: 'AI products for engineering productivity and software development workflows.', |
| 39 | keywords: ['api', 'sdk', 'cli', 'developer', 'devops', 'repository', 'integration', 'automation'], |
| 40 | }, |
| 41 | { |
| 42 | name: 'LLMs', |
| 43 | icon: 'Brain', |
| 44 | description: 'Large language model platforms, tooling, and educational resources.', |
| 45 | keywords: ['llm', 'large language model', 'foundation model', 'transformer', 'gpt', 'claude', 'gemini', 'llama', 'mistral'], |
| 46 | }, |
| 47 | { |
| 48 | name: 'Natural Language Processing', |
| 49 | icon: 'Languages', |
| 50 | description: 'AI for text understanding, language analysis, and semantic processing.', |
| 51 | keywords: ['nlp', 'language understanding', 'text analysis', 'sentiment', 'entity extraction', 'classification', 'summarization'], |
| 52 | }, |
| 53 | { |
| 54 | name: 'Prompt Engineering', |
| 55 | icon: 'MessageSquareQuote', |
| 56 | description: 'Techniques and tools for designing effective AI prompts and prompt workflows.', |
| 57 | keywords: ['prompt', 'prompting', 'prompt engineering', 'system prompt', 'instruction tuning', 'few-shot'], |
| 58 | }, |
| 59 | { |
| 60 | name: 'Chatbots', |
| 61 | icon: 'MessageCircle', |
| 62 | description: 'Conversational AI assistants, chatbot frameworks, and support tools.', |
| 63 | keywords: ['chatbot', 'assistant', 'conversation', 'customer support', 'chat', 'agent'], |
| 64 | }, |
| 65 | { |
| 66 | name: 'Agent Frameworks', |
| 67 | icon: 'Bot', |
| 68 | description: 'Frameworks and platforms for autonomous and multi-step AI agents.', |
| 69 | keywords: ['agent framework', 'autonomous agent', 'tool use', 'orchestration', 'multi-agent', 'agentic'], |
| 70 | }, |
| 71 | { |
| 72 | name: 'Image Generation', |
| 73 | icon: 'Image', |
| 74 | description: 'AI tools and resources for creating images, illustrations, and visual assets.', |
| 75 | keywords: ['image generation', 'text to image', 'midjourney', 'stable diffusion', 'dall-e', 'illustration', 'photo', 'art'], |
| 76 | }, |
| 77 | { |
| 78 | name: 'Computer Vision', |
| 79 | icon: 'ScanEye', |
| 80 | description: 'AI systems for visual understanding, object detection, and image analysis.', |
| 81 | keywords: ['computer vision', 'object detection', 'segmentation', 'ocr', 'vision model', 'image recognition'], |
| 82 | }, |
| 83 | { |
| 84 | name: 'Video Generation', |
| 85 | icon: 'Clapperboard', |
| 86 | description: 'AI for generating, editing, and transforming video content.', |
| 87 | keywords: ['video generation', 'text to video', 'video editing', 'animation', 'sora', 'runway'], |
| 88 | }, |
| 89 | { |
| 90 | name: 'Audio Generation', |
| 91 | icon: 'Music2', |
| 92 | description: 'AI tools for creating music, sound effects, and synthetic audio.', |
| 93 | keywords: ['audio generation', 'music generation', 'sound design', 'voice clone', 'sound effects'], |
| 94 | }, |
| 95 | { |
| 96 | name: 'Speech Recognition', |
| 97 | icon: 'Mic', |
| 98 | description: 'Speech-to-text and spoken language understanding systems.', |
| 99 | keywords: ['speech recognition', 'speech-to-text', 'stt', 'transcribe', 'dictation', 'voice recognition'], |
| 100 | }, |
| 101 | { |
| 102 | name: 'Text-to-Speech', |
| 103 | icon: 'Volume2', |
| 104 | description: 'Systems that synthesize natural speech from text.', |
| 105 | keywords: ['text-to-speech', 'tts', 'speech synthesis', 'voice synthesis', 'narration'], |
| 106 | }, |
| 107 | { |
| 108 | name: 'Data Science', |
| 109 | icon: 'BarChart3', |
| 110 | description: 'AI applications for data analysis, statistics, and analytical workflows.', |
| 111 | keywords: ['data science', 'analytics', 'dashboard', 'statistics', 'data analysis', 'notebook'], |
| 112 | }, |
| 113 | { |
| 114 | name: 'Machine Learning', |
| 115 | icon: 'Cpu', |
| 116 | description: 'Practical ML methods, tooling, model training, and deployment.', |
| 117 | keywords: ['machine learning', 'ml', 'model training', 'feature engineering', 'prediction', 'classification'], |
| 118 | }, |
| 119 | { |
| 120 | name: 'Deep Learning', |
| 121 | icon: 'Network', |
| 122 | description: 'Neural network architectures, training techniques, and DL applications.', |
| 123 | keywords: ['deep learning', 'neural network', 'cnn', 'rnn', 'attention', 'backpropagation'], |
| 124 | }, |
| 125 | { |
| 126 | name: 'MLOps', |
| 127 | icon: 'Workflow', |
| 128 | description: 'Infrastructure and lifecycle management for ML and AI models in production.', |
| 129 | keywords: ['mlops', 'model deployment', 'monitoring', 'model registry', 'pipeline', 'serving'], |
| 130 | }, |
| 131 | { |
| 132 | name: 'Workflow Automation', |
| 133 | icon: 'GitBranch', |
| 134 | description: 'AI-powered automation for repetitive and multi-step workflows.', |
| 135 | keywords: ['workflow', 'automation', 'zapier', 'make.com', 'n8n', 'pipeline', 'automate'], |
| 136 | }, |
| 137 | { |
| 138 | name: 'Search', |
| 139 | icon: 'Search', |
| 140 | description: 'Semantic, vector, and AI-assisted search technologies.', |
| 141 | keywords: ['search', 'semantic search', 'vector search', 'retrieval', 'rag', 'indexing'], |
| 142 | }, |
| 143 | { |
| 144 | name: 'Research', |
| 145 | icon: 'FlaskConical', |
| 146 | description: 'AI research platforms, methods, and academic learning resources.', |
| 147 | keywords: ['research', 'paper', 'benchmark', 'evaluation', 'study', 'experiment'], |
| 148 | }, |
| 149 | { |
| 150 | name: 'Writing Assistance', |
| 151 | icon: 'PenSquare', |
| 152 | description: 'AI writing assistants for drafting, editing, and content generation.', |
| 153 | keywords: ['writing', 'copywriting', 'grammar', 'blog', 'content', 'draft', 'rewrite'], |
| 154 | }, |
| 155 | { |
| 156 | name: 'Productivity', |
| 157 | icon: 'Briefcase', |
| 158 | description: 'AI tools that improve knowledge work and business productivity.', |
| 159 | keywords: ['productivity', 'task management', 'notes', 'meeting', 'email', 'workflow'], |
| 160 | }, |
| 161 | { |
| 162 | name: 'No-Code AI', |
| 163 | icon: 'Puzzle', |
| 164 | description: 'No-code and low-code AI builders for non-developer workflows.', |
| 165 | keywords: ['no-code', 'low-code', 'drag and drop', 'builder', 'visual workflow'], |
| 166 | }, |
| 167 | { |
| 168 | name: 'APIs', |
| 169 | icon: 'Plug', |
| 170 | description: 'API-first AI services, platforms, and integration layers.', |
| 171 | keywords: ['api', 'endpoint', 'rest', 'webhook', 'integration', 'platform'], |
| 172 | }, |
| 173 | { |
| 174 | name: 'Courses', |
| 175 | icon: 'GraduationCap', |
| 176 | description: 'Structured learning courses focused on AI topics and practical skills.', |
| 177 | keywords: ['course', 'curriculum', 'bootcamp', 'class', 'certification'], |
| 178 | }, |
| 179 | { |
| 180 | name: 'Tutorials', |
| 181 | icon: 'BookOpen', |
| 182 | description: 'Step-by-step tutorials and guides for building with AI.', |
| 183 | keywords: ['tutorial', 'guide', 'how to', 'walkthrough', 'hands-on'], |
| 184 | }, |
| 185 | { |
| 186 | name: 'Documentation', |
| 187 | icon: 'FileText', |
| 188 | description: 'Technical documentation, references, and implementation guides for AI products.', |
| 189 | keywords: ['documentation', 'docs', 'reference', 'quickstart', 'manual'], |
| 190 | }, |
| 191 | { |
| 192 | name: 'Ethics & Safety', |
| 193 | icon: 'ShieldCheck', |
| 194 | description: 'Responsible AI, alignment, safety engineering, and governance.', |
| 195 | keywords: ['safety', 'ethics', 'alignment', 'responsible ai', 'risk', 'governance'], |
| 196 | }, |
| 197 | { |
| 198 | name: 'Open Source', |
| 199 | icon: 'Github', |
| 200 | description: 'Open-source AI models, frameworks, and community resources.', |
| 201 | keywords: ['open source', 'oss', 'github', 'gitlab', 'apache', 'mit license'], |
| 202 | }, |
| 203 | ]; |
| 204 | |
| 205 | const GENERIC_CATEGORY_NAMES = new Set([ |
| 206 | 'general ai', |
| 207 | 'general', |
| 208 | 'other', |
| 209 | 'misc', |
| 210 | 'miscellaneous', |
| 211 | 'ai', |
| 212 | 'artificial intelligence', |
| 213 | 'ai tools', |
| 214 | 'all', |
| 215 | 'uncategorized', |
| 216 | ]); |
| 217 | |
| 218 | const TOOL_FALLBACK_TAGS = ['LLMs', 'Productivity', 'Workflow Automation']; |
| 219 | const LEARNING_FALLBACK_TAGS = ['Machine Learning', 'Natural Language Processing', 'Prompt Engineering']; |
| 220 | |
| 221 | function normalize(value) { |
| 222 | return String(value || '').trim().toLowerCase(); |
| 223 | } |
| 224 | |
| 225 | function slugify(value) { |
| 226 | return String(value || '') |
| 227 | .toLowerCase() |
| 228 | .replace(/[^a-z0-9]+/g, '-') |
| 229 | .replace(/(^-|-$)+/g, '') |
| 230 | .slice(0, 80); |
| 231 | } |
| 232 | |
| 233 | function isGenericCategory(name) { |
| 234 | const n = normalize(name); |
| 235 | if (!n) return true; |
| 236 | if (GENERIC_CATEGORY_NAMES.has(n)) return true; |
| 237 | if (n === 'general ai tools') return true; |
| 238 | if (n.startsWith('general ')) return true; |
| 239 | return false; |
| 240 | } |
| 241 | |
| 242 | function containsKeyword(text, keyword) { |
| 243 | const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); |
| 244 | const regex = new RegExp(`(^|[^a-z0-9])${escaped}([^a-z0-9]|$)`, 'i'); |
| 245 | return regex.test(text); |
| 246 | } |
| 247 | |
| 248 | function inferTagScores({ name, description, url, kind }) { |
| 249 | const text = `${name || ''} ${description || ''}`.toLowerCase(); |
| 250 | const urlText = String(url || '').toLowerCase(); |
| 251 | const scores = new Map(); |
| 252 | |
| 253 | for (const def of TAG_DEFINITIONS) { |
| 254 | let score = 0; |
| 255 | for (const keyword of def.keywords) { |
| 256 | if (containsKeyword(text, keyword.toLowerCase())) { |
| 257 | score += keyword.includes(' ') ? 3 : 2; |
| 258 | } |
| 259 | if (containsKeyword(urlText, keyword.toLowerCase())) { |
| 260 | score += 1; |
| 261 | } |
| 262 | } |
| 263 | |
| 264 | if (def.name === 'Open Source' && (urlText.includes('github.com') || urlText.includes('gitlab.com'))) { |
| 265 | score += 4; |
| 266 | } |
| 267 | |
| 268 | if (def.name === 'Courses' && kind === 'learning') { |
| 269 | if (containsKeyword(text, 'course') || containsKeyword(text, 'curriculum')) score += 3; |
| 270 | } |
| 271 | |
| 272 | if (def.name === 'Tutorials' && kind === 'learning') { |
| 273 | if (containsKeyword(text, 'tutorial') || containsKeyword(text, 'guide') || containsKeyword(text, 'walkthrough')) score += 3; |
| 274 | } |
| 275 | |
| 276 | if (def.name === 'Documentation' && kind === 'learning') { |
| 277 | if (containsKeyword(text, 'documentation') || containsKeyword(text, 'docs') || containsKeyword(text, 'reference')) score += 3; |
| 278 | } |
| 279 | |
| 280 | if (score > 0) { |
| 281 | scores.set(def.name, score); |
| 282 | } |
| 283 | } |
| 284 | |
| 285 | return Array.from(scores.entries()) |
| 286 | .sort((a, b) => b[1] - a[1]) |
| 287 | .map(([tag]) => tag); |
| 288 | } |
| 289 | |
| 290 | async function fetchAllRows(table, columns) { |
| 291 | const pageSize = 1000; |
| 292 | let from = 0; |
| 293 | const rows = []; |
| 294 | |
| 295 | while (true) { |
| 296 | const to = from + pageSize - 1; |
| 297 | const { data, error } = await supabase.from(table).select(columns).range(from, to); |
| 298 | |
| 299 | if (error) { |
| 300 | throw new Error(`Failed to fetch ${table}: ${error.message}`); |
| 301 | } |
| 302 | |
| 303 | if (!data || data.length === 0) { |
| 304 | break; |
| 305 | } |
| 306 | |
| 307 | rows.push(...data); |
| 308 | |
| 309 | if (data.length < pageSize) { |
| 310 | break; |
| 311 | } |
| 312 | |
| 313 | from += pageSize; |
| 314 | } |
| 315 | |
| 316 | return rows; |
| 317 | } |
| 318 | |
| 319 | async function detectLearningTable() { |
| 320 | const candidates = ['learning', 'learning_resources']; |
| 321 | for (const table of candidates) { |
| 322 | try { |
| 323 | await fetchAllRows(table, 'id'); |
| 324 | return table; |
| 325 | } catch (error) { |
| 326 | const message = error instanceof Error ? error.message : String(error); |
| 327 | if (!message.includes('Could not find the table')) { |
| 328 | throw error; |
| 329 | } |
| 330 | } |
| 331 | } |
| 332 | |
| 333 | throw new Error('Could not find learning table: tried learning, learning_resources'); |
| 334 | } |
| 335 | |
| 336 | async function detectLearningCategoryIdColumn() { |
| 337 | const candidates = ['learning_id', 'learning_resource_id']; |
| 338 | for (const col of candidates) { |
| 339 | const { error } = await supabase.from('learning_categories').select(`${col}`).limit(1); |
| 340 | if (!error) { |
| 341 | return col; |
| 342 | } |
| 343 | if (!String(error.message || '').includes('column')) { |
| 344 | throw new Error(`Unable to inspect learning_categories column ${col}: ${error.message}`); |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | throw new Error('Could not find learning id column in learning_categories table'); |
| 349 | } |
| 350 | |
| 351 | async function loadData() { |
| 352 | const learningTable = await detectLearningTable(); |
| 353 | const learningIdColumn = await detectLearningCategoryIdColumn(); |
| 354 | |
| 355 | const [categories, tools, learningResources, toolLinks, learningLinks] = await Promise.all([ |
| 356 | fetchAllRows('categories', 'id, name, slug, icon, description'), |
| 357 | fetchAllRows('tools', 'id, name, description, url'), |
| 358 | fetchAllRows(learningTable, 'id, title, description, url'), |
| 359 | fetchAllRows('tools_categories', 'tool_id, category_id, is_primary'), |
| 360 | fetchAllRows('learning_categories', `${learningIdColumn}, category_id, is_primary`), |
| 361 | ]); |
| 362 | |
| 363 | return { categories, tools, learningResources, toolLinks, learningLinks, learningTable, learningIdColumn }; |
| 364 | } |
| 365 | |
| 366 | function buildCategoryIndexes(categories) { |
| 367 | const byName = new Map(); |
| 368 | const bySlug = new Map(); |
| 369 | const byId = new Map(); |
| 370 | |
| 371 | for (const category of categories) { |
| 372 | byName.set(normalize(category.name), category); |
| 373 | bySlug.set(normalize(category.slug), category); |
| 374 | byId.set(category.id, category); |
| 375 | } |
| 376 | |
| 377 | return { byName, bySlug, byId }; |
| 378 | } |
| 379 | |
| 380 | function uniqueName(items) { |
| 381 | const seen = new Set(); |
| 382 | return items.filter((v) => { |
| 383 | const key = normalize(v); |
| 384 | if (!key || seen.has(key)) return false; |
| 385 | seen.add(key); |
| 386 | return true; |
| 387 | }); |
| 388 | } |
| 389 | |
| 390 | async function ensureCategory(tagName, indexes, createdCategories) { |
| 391 | const existing = indexes.byName.get(normalize(tagName)); |
| 392 | if (existing) return existing; |
| 393 | |
| 394 | const def = TAG_DEFINITIONS.find((t) => t.name === tagName); |
| 395 | const baseSlug = slugify(tagName); |
| 396 | let slug = baseSlug; |
| 397 | let counter = 2; |
| 398 | |
| 399 | while (indexes.bySlug.has(normalize(slug))) { |
| 400 | slug = `${baseSlug}-${counter}`; |
| 401 | counter += 1; |
| 402 | } |
| 403 | |
| 404 | const payload = { |
| 405 | name: tagName, |
| 406 | slug, |
| 407 | icon: def?.icon || 'Tag', |
| 408 | description: def?.description || `Category for ${tagName}`, |
| 409 | }; |
| 410 | |
| 411 | const { data, error } = await supabase |
| 412 | .from('categories') |
| 413 | .insert(payload) |
| 414 | .select('id, name, slug, icon, description') |
| 415 | .single(); |
| 416 | |
| 417 | if (error) { |
| 418 | throw new Error(`Failed to create category "${tagName}": ${error.message}`); |
| 419 | } |
| 420 | |
| 421 | indexes.byName.set(normalize(data.name), data); |
| 422 | indexes.bySlug.set(normalize(data.slug), data); |
| 423 | indexes.byId.set(data.id, data); |
| 424 | createdCategories.push(data); |
| 425 | |
| 426 | console.log(`[create-category] ${data.name} (id=${data.id}, slug=${data.slug}, icon=${data.icon})`); |
| 427 | |
| 428 | return data; |
| 429 | } |
| 430 | |
| 431 | function buildLinksByItem(links, itemKey) { |
| 432 | const map = new Map(); |
| 433 | for (const row of links) { |
| 434 | const id = row[itemKey]; |
| 435 | if (!map.has(id)) map.set(id, []); |
| 436 | map.get(id).push(row); |
| 437 | } |
| 438 | return map; |
| 439 | } |
| 440 | |
| 441 | function pickFinalTagNames({ currentCategoryNames, primaryCurrentName, inferredNames, kind }) { |
| 442 | const currentSpecific = currentCategoryNames.filter((name) => !isGenericCategory(name)); |
| 443 | const fallback = kind === 'tool' ? TOOL_FALLBACK_TAGS : LEARNING_FALLBACK_TAGS; |
| 444 | |
| 445 | const final = []; |
| 446 | |
| 447 | if (primaryCurrentName && !isGenericCategory(primaryCurrentName)) { |
| 448 | final.push(primaryCurrentName); |
| 449 | } |
| 450 | |
| 451 | for (const name of currentSpecific) { |
| 452 | final.push(name); |
| 453 | } |
| 454 | |
| 455 | if (final.length < 3) { |
| 456 | for (const name of inferredNames) { |
| 457 | final.push(name); |
| 458 | if (uniqueName(final).length >= 3) break; |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | if (uniqueName(final).length < 3) { |
| 463 | for (const name of fallback) { |
| 464 | final.push(name); |
| 465 | if (uniqueName(final).length >= 3) break; |
| 466 | } |
| 467 | } |
| 468 | |
| 469 | let deduped = uniqueName(final); |
| 470 | |
| 471 | if (deduped.length < 3) { |
| 472 | for (const name of TAG_DEFINITIONS.map((d) => d.name)) { |
| 473 | deduped.push(name); |
| 474 | deduped = uniqueName(deduped); |
| 475 | if (deduped.length >= 3) break; |
| 476 | } |
| 477 | } |
| 478 | |
| 479 | if (deduped.length < 3) { |
| 480 | throw new Error('Unable to generate at least 3 tags for item'); |
| 481 | } |
| 482 | |
| 483 | if (deduped.length > 5) { |
| 484 | const currentSpecificSet = new Set(currentSpecific.map(normalize)); |
| 485 | const mustKeep = deduped.filter((name) => currentSpecificSet.has(normalize(name))); |
| 486 | |
| 487 | if (mustKeep.length > 5) { |
| 488 | // Preserve all existing specific tags to avoid deleting valid tags. |
| 489 | return mustKeep; |
| 490 | } |
| 491 | |
| 492 | const extras = deduped.filter((name) => !currentSpecificSet.has(normalize(name))); |
| 493 | deduped = [...mustKeep, ...extras].slice(0, 5); |
| 494 | } |
| 495 | |
| 496 | return deduped; |
| 497 | } |
| 498 | |
| 499 | function pickPrimaryTagName({ finalNames, inferredNames, currentPrimaryName }) { |
| 500 | if (currentPrimaryName && finalNames.some((n) => normalize(n) === normalize(currentPrimaryName))) { |
| 501 | return finalNames.find((n) => normalize(n) === normalize(currentPrimaryName)); |
| 502 | } |
| 503 | |
| 504 | for (const inferred of inferredNames) { |
| 505 | const found = finalNames.find((n) => normalize(n) === normalize(inferred)); |
| 506 | if (found) return found; |
| 507 | } |
| 508 | |
| 509 | return finalNames[0]; |
| 510 | } |
| 511 | |
| 512 | async function reconcileItem({ |
| 513 | kind, |
| 514 | item, |
| 515 | itemName, |
| 516 | itemDescription, |
| 517 | itemUrl, |
| 518 | itemIdKey, |
| 519 | junctionTable, |
| 520 | linkRows, |
| 521 | indexes, |
| 522 | createdCategories, |
| 523 | summary, |
| 524 | }) { |
| 525 | const currentCategoryRows = linkRows.map((row) => { |
| 526 | const category = indexes.byId.get(row.category_id); |
| 527 | return { |
| 528 | categoryId: row.category_id, |
| 529 | categoryName: category?.name || `Unknown(${row.category_id})`, |
| 530 | isPrimary: !!row.is_primary, |
| 531 | }; |
| 532 | }); |
| 533 | |
| 534 | const currentCategoryNames = currentCategoryRows.map((row) => row.categoryName); |
| 535 | const currentPrimary = currentCategoryRows.find((row) => row.isPrimary); |
| 536 | const currentPrimaryName = currentPrimary?.categoryName; |
| 537 | |
| 538 | const inferredNames = inferTagScores({ |
| 539 | name: itemName, |
| 540 | description: itemDescription, |
| 541 | url: itemUrl, |
| 542 | kind: kind === 'tool' ? 'tool' : 'learning', |
| 543 | }); |
| 544 | |
| 545 | const finalTagNames = pickFinalTagNames({ |
| 546 | currentCategoryNames, |
| 547 | primaryCurrentName: currentPrimaryName, |
| 548 | inferredNames, |
| 549 | kind, |
| 550 | }); |
| 551 | |
| 552 | const primaryTagName = pickPrimaryTagName({ |
| 553 | finalNames: finalTagNames, |
| 554 | inferredNames, |
| 555 | currentPrimaryName, |
| 556 | }); |
| 557 | |
| 558 | const finalCategories = []; |
| 559 | for (const tagName of finalTagNames) { |
| 560 | const category = await ensureCategory(tagName, indexes, createdCategories); |
| 561 | finalCategories.push(category); |
| 562 | } |
| 563 | |
| 564 | const finalCategoryIds = new Set(finalCategories.map((c) => c.id)); |
| 565 | const currentCategoryIds = new Set(currentCategoryRows.map((c) => c.categoryId)); |
| 566 | |
| 567 | const toAdd = finalCategories.filter((cat) => !currentCategoryIds.has(cat.id)); |
| 568 | |
| 569 | const removableGenericIds = currentCategoryRows |
| 570 | .filter((row) => isGenericCategory(row.categoryName)) |
| 571 | .map((row) => row.categoryId) |
| 572 | .filter((id) => !finalCategoryIds.has(id)); |
| 573 | |
| 574 | const removeIds = Array.from(new Set(removableGenericIds)); |
| 575 | |
| 576 | if (toAdd.length > 0) { |
| 577 | const payload = toAdd.map((cat) => ({ |
| 578 | [itemIdKey]: item.id, |
| 579 | category_id: cat.id, |
| 580 | is_primary: false, |
| 581 | })); |
| 582 | |
| 583 | const { error } = await supabase.from(junctionTable).insert(payload); |
| 584 | if (error) { |
| 585 | throw new Error(`Failed adding ${kind} categories for ${item.id}: ${error.message}`); |
| 586 | } |
| 587 | } |
| 588 | |
| 589 | if (removeIds.length > 0) { |
| 590 | const { error } = await supabase |
| 591 | .from(junctionTable) |
| 592 | .delete() |
| 593 | .eq(itemIdKey, item.id) |
| 594 | .in('category_id', removeIds); |
| 595 | |
| 596 | if (error) { |
| 597 | throw new Error(`Failed removing generic ${kind} categories for ${item.id}: ${error.message}`); |
| 598 | } |
| 599 | } |
| 600 | |
| 601 | const primaryCategory = finalCategories.find((c) => normalize(c.name) === normalize(primaryTagName)); |
| 602 | if (!primaryCategory) { |
| 603 | throw new Error(`Primary category not found for ${kind} ${item.id}`); |
| 604 | } |
| 605 | |
| 606 | const { error: clearPrimaryError } = await supabase |
| 607 | .from(junctionTable) |
| 608 | .update({ is_primary: false }) |
| 609 | .eq(itemIdKey, item.id); |
| 610 | |
| 611 | if (clearPrimaryError) { |
| 612 | throw new Error(`Failed clearing primary on ${kind} ${item.id}: ${clearPrimaryError.message}`); |
| 613 | } |
| 614 | |
| 615 | const { error: setPrimaryError } = await supabase |
| 616 | .from(junctionTable) |
| 617 | .update({ is_primary: true }) |
| 618 | .eq(itemIdKey, item.id) |
| 619 | .eq('category_id', primaryCategory.id); |
| 620 | |
| 621 | if (setPrimaryError) { |
| 622 | throw new Error(`Failed setting primary on ${kind} ${item.id}: ${setPrimaryError.message}`); |
| 623 | } |
| 624 | |
| 625 | const beforeSpecificCount = currentCategoryRows.filter((row) => !isGenericCategory(row.categoryName)).length; |
| 626 | const changed = |
| 627 | toAdd.length > 0 || |
| 628 | removeIds.length > 0 || |
| 629 | !currentPrimary || |
| 630 | normalize(currentPrimary.categoryName) !== normalize(primaryCategory.name) || |
| 631 | beforeSpecificCount < 3; |
| 632 | |
| 633 | if (changed) { |
| 634 | summary.changedItems += 1; |
| 635 | summary.addedLinks += toAdd.length; |
| 636 | summary.removedLinks += removeIds.length; |
| 637 | summary.primaryUpdates += 1; |
| 638 | |
| 639 | const removedNames = removeIds |
| 640 | .map((id) => indexes.byId.get(id)?.name) |
| 641 | .filter(Boolean); |
| 642 | |
| 643 | const finalNames = finalCategories.map((c) => c.name); |
| 644 | |
| 645 | console.log( |
| 646 | `[update-${kind}] id=${item.id} name="${itemName}" add=[${toAdd.map((c) => c.name).join(', ')}] remove=[${removedNames.join(', ')}] primary="${primaryCategory.name}" final=[${finalNames.join(', ')}]` |
| 647 | ); |
| 648 | } |
| 649 | |
| 650 | if (finalCategories.length < 3) { |
| 651 | summary.lowTagItems.push({ kind, id: item.id, name: itemName, count: finalCategories.length }); |
| 652 | } |
| 653 | |
| 654 | if (finalCategories.length > 5) { |
| 655 | summary.highTagItems.push({ kind, id: item.id, name: itemName, count: finalCategories.length }); |
| 656 | } |
| 657 | } |
| 658 | |
| 659 | async function auditAndFixTags() { |
| 660 | console.log('Starting audit and tag-fix for tools and learning resources...'); |
| 661 | |
| 662 | const { categories, tools, learningResources, toolLinks, learningLinks, learningTable, learningIdColumn } = await loadData(); |
| 663 | const indexes = buildCategoryIndexes(categories); |
| 664 | const createdCategories = []; |
| 665 | |
| 666 | console.log( |
| 667 | `Loaded ${categories.length} categories, ${tools.length} tools, ${learningResources.length} learning resources from ${learningTable}, ${toolLinks.length} tool links, ${learningLinks.length} learning links (id column: ${learningIdColumn}).` |
| 668 | ); |
| 669 | |
| 670 | const toolLinksByToolId = buildLinksByItem(toolLinks, 'tool_id'); |
| 671 | const learningLinksByLearningId = buildLinksByItem(learningLinks, learningIdColumn); |
| 672 | |
| 673 | const summary = { |
| 674 | changedItems: 0, |
| 675 | addedLinks: 0, |
| 676 | removedLinks: 0, |
| 677 | primaryUpdates: 0, |
| 678 | lowTagItems: [], |
| 679 | highTagItems: [], |
| 680 | }; |
| 681 | |
| 682 | for (const tool of tools) { |
| 683 | await reconcileItem({ |
| 684 | kind: 'tool', |
| 685 | item: tool, |
| 686 | itemName: tool.name || `Tool ${tool.id}`, |
| 687 | itemDescription: tool.description || '', |
| 688 | itemUrl: tool.url || '', |
| 689 | itemIdKey: 'tool_id', |
| 690 | junctionTable: 'tools_categories', |
| 691 | linkRows: toolLinksByToolId.get(tool.id) || [], |
| 692 | indexes, |
| 693 | createdCategories, |
| 694 | summary, |
| 695 | }); |
| 696 | } |
| 697 | |
| 698 | for (const learning of learningResources) { |
| 699 | await reconcileItem({ |
| 700 | kind: 'learning', |
| 701 | item: learning, |
| 702 | itemName: learning.title || `Learning ${learning.id}`, |
| 703 | itemDescription: learning.description || '', |
| 704 | itemUrl: learning.url || '', |
| 705 | itemIdKey: learningIdColumn, |
| 706 | junctionTable: 'learning_categories', |
| 707 | linkRows: learningLinksByLearningId.get(learning.id) || [], |
| 708 | indexes, |
| 709 | createdCategories, |
| 710 | summary, |
| 711 | }); |
| 712 | } |
| 713 | |
| 714 | console.log('--- Summary ---'); |
| 715 | console.log(`Created categories: ${createdCategories.length}`); |
| 716 | console.log(`Changed items: ${summary.changedItems}`); |
| 717 | console.log(`Added links: ${summary.addedLinks}`); |
| 718 | console.log(`Removed generic links: ${summary.removedLinks}`); |
| 719 | console.log(`Primary updates: ${summary.primaryUpdates}`); |
| 720 | |
| 721 | if (summary.lowTagItems.length > 0) { |
| 722 | console.log(`Items under 3 tags: ${summary.lowTagItems.length}`); |
| 723 | for (const item of summary.lowTagItems.slice(0, 25)) { |
| 724 | console.log(` - [${item.kind}] id=${item.id} name="${item.name}" count=${item.count}`); |
| 725 | } |
| 726 | } |
| 727 | |
| 728 | if (summary.highTagItems.length > 0) { |
| 729 | console.log(`Items over 5 tags (preserved existing specific tags): ${summary.highTagItems.length}`); |
| 730 | for (const item of summary.highTagItems.slice(0, 25)) { |
| 731 | console.log(` - [${item.kind}] id=${item.id} name="${item.name}" count=${item.count}`); |
| 732 | } |
| 733 | } |
| 734 | |
| 735 | console.log('Audit complete.'); |
| 736 | } |
| 737 | |
| 738 | await auditAndFixTags(); |