import dotenv from "dotenv"; import { createClient } from "@supabase/supabase-js"; dotenv.config({ path: ".env" }); const BATCH_SIZE = 10; function toLines(value) { if (!value) return []; if (Array.isArray(value)) { return value.map((v) => String(v).trim()).filter(Boolean); } return String(value) .split(/\r?\n|[.;]\s+/) .map((line) => line.replace(/^[-*]\s*/, "").trim()) .filter(Boolean); } function cleanSentence(value, fallback = "") { if (!value) return fallback; const first = String(value).replace(/\s+/g, " ").trim(); return first.endsWith(".") ? first.slice(0, -1) : first; } function clamp(value, min, max) { return Math.max(min, Math.min(max, value)); } function inferPrimaryUseCase(tool, categoryName) { const text = [ tool.name, tool.description, tool.long_description, tool.key_features, categoryName || "", ] .filter(Boolean) .join(" ") .toLowerCase(); const rules = [ { re: /\b(image|art|design|visual|photo)\b/, useCase: "generate and edit visual content" }, { re: /\b(video|avatar|subtitle|caption)\b/, useCase: "create and refine video content" }, { re: /\b(code|developer|programming|debug|repository|github)\b/, useCase: "build and ship code faster" }, { re: /\b(meeting|transcri|notes)\b/, useCase: "capture and summarize meetings quickly" }, { re: /\b(search|research|knowledge|answer engine)\b/, useCase: "research and summarize information quickly" }, { re: /\b(agent|workflow|automation|orchestrat)\b/, useCase: "automate multi-step workflows" }, { re: /\b(marketing|copy|seo|ad copy|campaign)\b/, useCase: "draft and optimize marketing content" }, { re: /\b(presentation|slides|deck)\b/, useCase: "build polished presentations quickly" }, { re: /\b(chatbot|assistant|llm|chat)\b/, useCase: "draft, analyze, and iterate with AI assistance" }, { re: /\b(data|analytics|dashboard|business intelligence)\b/, useCase: "analyze data and produce actionable insights" }, ]; const matched = rules.find((rule) => rule.re.test(text)); if (matched) return matched.useCase; const featureLine = toLines(tool.key_features)[0]; if (featureLine) { return cleanSentence(featureLine, "complete core tasks faster").toLowerCase(); } return "complete core tasks faster"; } function inferTimeEstimateMinutes(tool) { const text = [tool.description, tool.key_features, tool.pricing, tool.deployment] .filter(Boolean) .join(" ") .toLowerCase(); let minutes = 20; if (/\b(self-hosted|open-source|api|developer|enterprise)\b/.test(text)) minutes += 5; if (/\b(complex|advanced|learning curve)\b/.test(text)) minutes += 5; if (/\b(no-code|easy|simple|beginner|quick)\b/.test(text)) minutes -= 5; return Math.round(clamp(minutes, 10, 35) / 5) * 5; } function deriveCostToStart(pricing) { const text = (pricing || "").toLowerCase(); if (!text) return "Check vendor pricing"; if (text.includes("free trial")) return "Free trial"; if (text.includes("freemium")) return "Free plan available"; if (text.includes("open-source") && /\b(cloud|paid|subscription|plan)\b/.test(text)) { return "Free (self-hosted) or paid cloud plans"; } if (text.includes("open-source")) return "Free (open-source)"; if (text.includes("free") && /\b(pro|paid|subscription|plan)\b/.test(text)) return "Free plan available"; if (text.includes("free")) return "Free"; if (/\b(contact sales|enterprise)\b/.test(text)) return "Paid (contact sales)"; if (/\$\s?\d+/.test(text)) { const price = pricing.match(/\$\s?\d+(?:\.\d+)?(?:\s*\/\s*(?:mo|month|year|yr))?/i)?.[0]; return price ? `Starts at ${price.replace(/\s+/g, " ")}` : "Paid plans"; } if (/\b(paid|subscription|plan)\b/.test(text)) return "Paid plans"; return "Check vendor pricing"; } function inferSetupTime(tool) { const text = [tool.pricing, tool.deployment, tool.key_features, tool.cons] .filter(Boolean) .join(" ") .toLowerCase(); if (/\b(self-hosted|open-source|api|developer)\b/.test(text)) return "15-20 minutes"; if (/\b(enterprise|integration|complex)\b/.test(text)) return "10-15 minutes"; return "5-10 minutes"; } function pickAlternatives(toolName, categoryName, description) { const text = `${categoryName || ""} ${description || ""}`.toLowerCase(); const mappings = [ { re: /\b(llm|assistant|chat|chatbot)\b/, options: ["ChatGPT", "Claude", "Perplexity"] }, { re: /\b(image|art|visual|design)\b/, options: ["Midjourney", "DALLĀ·E 3", "Stable Diffusion"] }, { re: /\b(video|avatar|editing|subtitle)\b/, options: ["Runway", "Synthesia", "Descript"] }, { re: /\b(code|developer|programming|debug)\b/, options: ["GitHub Copilot", "Cursor", "Codeium"] }, { re: /\b(automation|workflow|agent|orchestration)\b/, options: ["Zapier", "Make", "n8n"] }, { re: /\b(marketing|copy|seo|campaign)\b/, options: ["Jasper", "Copy.ai", "Writesonic"] }, { re: /\b(presentation|slides|deck)\b/, options: ["Gamma", "Canva", "Beautiful.ai"] }, { re: /\b(meeting|transcri|notes)\b/, options: ["Otter.ai", "Fireflies.ai", "Notion AI"] }, { re: /\b(data|analytics|dashboard|bi)\b/, options: ["Tableau", "Power BI", "Looker Studio"] }, { re: /\b(search|research|knowledge)\b/, options: ["Perplexity", "You.com", "ChatGPT"] }, ]; const fallback = ["ChatGPT", "Claude", "Perplexity"]; const matched = mappings.find((m) => m.re.test(text))?.options || fallback; const lowerName = (toolName || "").toLowerCase(); const unique = matched.filter((alt) => !lowerName.includes(alt.toLowerCase().replace(/[^\w]/g, ""))); return unique.slice(0, 3).length >= 2 ? unique.slice(0, 3) : fallback.slice(0, 3); } function generateOverview(tool, categoryName) { const time = inferTimeEstimateMinutes(tool); const useCase = inferPrimaryUseCase(tool, categoryName); const features = toLines(tool.key_features); const cons = toLines(tool.cons); const hero_headline = `Use ${tool.name} to ${useCase} in ${time} minutes`; const hero_subhead = features.length >= 2 ? `Start with one outcome, apply ${features[0].toLowerCase()}, then iterate with ${features[1].toLowerCase()} to get usable results quickly.` : `Start with one clear goal, add your context, and iterate with short prompts to get usable output fast.`; const best_for = features.length ? `${cleanSentence(features[0], "Practical day-to-day AI tasks")} and related workflows` : `${cleanSentence(tool.description, "Practical day-to-day AI tasks")}`; const not_for = cons.length ? cleanSentence(cons[0], "Teams that require guaranteed accuracy without manual verification") : "Tasks that require guaranteed accuracy without manual verification"; const quick_verdict = { best_for, not_for, setup_time: inferSetupTime(tool), cost_to_start: deriveCostToStart(tool.pricing), alternatives: pickAlternatives(tool.name, categoryName, tool.description), }; return { hero_headline, hero_subhead, hero_time_estimate_minutes: time, quick_verdict, }; } async function main() { const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL; const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY; if (!supabaseUrl || !serviceKey) { throw new Error("Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env"); } const supabase = createClient(supabaseUrl, serviceKey, { auth: { autoRefreshToken: false, persistSession: false }, }); const { data: categories, error: categoriesError } = await supabase .from("categories") .select("id,name"); if (categoriesError) throw new Error(`Failed to fetch categories: ${categoriesError.message}`); const categoryById = new Map((categories || []).map((c) => [c.id, c.name])); const { data: tools, error: toolsError } = await supabase .from("tools") .select("id,name,slug,description,long_description,url,pricing,key_features,pros,cons,primary_category_id,tutorial_enabled") .order("id", { ascending: true }); if (toolsError) throw new Error(`Failed to fetch tools: ${toolsError.message}`); const { data: overviews, error: overviewError } = await supabase .from("tool_tutorial_overviews") .select("tool_id"); if (overviewError) throw new Error(`Failed to fetch existing overviews: ${overviewError.message}`); const existingOverviewIds = new Set((overviews || []).map((row) => row.tool_id)); const pending = (tools || []).filter((tool) => !existingOverviewIds.has(tool.id)); console.log(`Total tools: ${(tools || []).length}`); console.log(`Existing overviews: ${existingOverviewIds.size}`); console.log(`Pending inserts: ${pending.length}`); console.log(`Batch size: ${BATCH_SIZE}`); let inserted = 0; let updated = 0; let failed = 0; for (let i = 0; i < pending.length; i += BATCH_SIZE) { const batch = pending.slice(i, i + BATCH_SIZE); const batchNum = Math.floor(i / BATCH_SIZE) + 1; const batchTotal = Math.ceil(pending.length / BATCH_SIZE); console.log(`\n[Batch ${batchNum}/${batchTotal}] Processing ${batch.length} tools...`); await Promise.all( batch.map(async (tool, idx) => { const itemNum = i + idx + 1; const label = `[${itemNum}/${pending.length}] ${tool.name} (id=${tool.id})`; try { const categoryName = categoryById.get(tool.primary_category_id) || null; const overview = generateOverview(tool, categoryName); const { error: insertError } = await supabase .from("tool_tutorial_overviews") .insert({ tool_id: tool.id, hero_headline: overview.hero_headline, hero_subhead: overview.hero_subhead, hero_time_estimate_minutes: overview.hero_time_estimate_minutes, quick_verdict: overview.quick_verdict, }); if (insertError) throw new Error(`insert overview failed: ${insertError.message}`); const { error: updateError } = await supabase .from("tools") .update({ tutorial_enabled: true }) .eq("id", tool.id); if (updateError) throw new Error(`update tutorial_enabled failed: ${updateError.message}`); inserted += 1; updated += 1; console.log(`${label} -> inserted + tutorial_enabled=true`); } catch (error) { failed += 1; const message = error instanceof Error ? error.message : String(error); console.error(`${label} -> FAILED: ${message}`); } }) ); } console.log("\nDone."); console.log(`Inserted overviews: ${inserted}`); console.log(`Updated tools.tutorial_enabled: ${updated}`); console.log(`Failures: ${failed}`); } main().catch((error) => { console.error(`Fatal error: ${error.message}`); process.exit(1); });