Branchwell

AI Resource Pro / website / scripts / populate-tutorials.js

1import dotenv from "dotenv";
2import { createClient } from "@supabase/supabase-js";
3
4dotenv.config({ path: ".env" });
5
6const BATCH_SIZE = 10;
7
8function toLines(value) {
9 if (!value) return [];
10 if (Array.isArray(value)) {
11 return value.map((v) => String(v).trim()).filter(Boolean);
12 }
13 return String(value)
14 .split(/\r?\n|[.;]\s+/)
15 .map((line) => line.replace(/^[-*]\s*/, "").trim())
16 .filter(Boolean);
17}
18
19function cleanSentence(value, fallback = "") {
20 if (!value) return fallback;
21 const first = String(value).replace(/\s+/g, " ").trim();
22 return first.endsWith(".") ? first.slice(0, -1) : first;
23}
24
25function clamp(value, min, max) {
26 return Math.max(min, Math.min(max, value));
27}
28
29function inferPrimaryUseCase(tool, categoryName) {
30 const text = [
31 tool.name,
32 tool.description,
33 tool.long_description,
34 tool.key_features,
35 categoryName || "",
36 ]
37 .filter(Boolean)
38 .join(" ")
39 .toLowerCase();
40
41 const rules = [
42 { re: /\b(image|art|design|visual|photo)\b/, useCase: "generate and edit visual content" },
43 { re: /\b(video|avatar|subtitle|caption)\b/, useCase: "create and refine video content" },
44 { re: /\b(code|developer|programming|debug|repository|github)\b/, useCase: "build and ship code faster" },
45 { re: /\b(meeting|transcri|notes)\b/, useCase: "capture and summarize meetings quickly" },
46 { re: /\b(search|research|knowledge|answer engine)\b/, useCase: "research and summarize information quickly" },
47 { re: /\b(agent|workflow|automation|orchestrat)\b/, useCase: "automate multi-step workflows" },
48 { re: /\b(marketing|copy|seo|ad copy|campaign)\b/, useCase: "draft and optimize marketing content" },
49 { re: /\b(presentation|slides|deck)\b/, useCase: "build polished presentations quickly" },
50 { re: /\b(chatbot|assistant|llm|chat)\b/, useCase: "draft, analyze, and iterate with AI assistance" },
51 { re: /\b(data|analytics|dashboard|business intelligence)\b/, useCase: "analyze data and produce actionable insights" },
52 ];
53
54 const matched = rules.find((rule) => rule.re.test(text));
55 if (matched) return matched.useCase;
56
57 const featureLine = toLines(tool.key_features)[0];
58 if (featureLine) {
59 return cleanSentence(featureLine, "complete core tasks faster").toLowerCase();
60 }
61
62 return "complete core tasks faster";
63}
64
65function inferTimeEstimateMinutes(tool) {
66 const text = [tool.description, tool.key_features, tool.pricing, tool.deployment]
67 .filter(Boolean)
68 .join(" ")
69 .toLowerCase();
70
71 let minutes = 20;
72 if (/\b(self-hosted|open-source|api|developer|enterprise)\b/.test(text)) minutes += 5;
73 if (/\b(complex|advanced|learning curve)\b/.test(text)) minutes += 5;
74 if (/\b(no-code|easy|simple|beginner|quick)\b/.test(text)) minutes -= 5;
75
76 return Math.round(clamp(minutes, 10, 35) / 5) * 5;
77}
78
79function deriveCostToStart(pricing) {
80 const text = (pricing || "").toLowerCase();
81 if (!text) return "Check vendor pricing";
82 if (text.includes("free trial")) return "Free trial";
83 if (text.includes("freemium")) return "Free plan available";
84 if (text.includes("open-source") && /\b(cloud|paid|subscription|plan)\b/.test(text)) {
85 return "Free (self-hosted) or paid cloud plans";
86 }
87 if (text.includes("open-source")) return "Free (open-source)";
88 if (text.includes("free") && /\b(pro|paid|subscription|plan)\b/.test(text)) return "Free plan available";
89 if (text.includes("free")) return "Free";
90 if (/\b(contact sales|enterprise)\b/.test(text)) return "Paid (contact sales)";
91 if (/\$\s?\d+/.test(text)) {
92 const price = pricing.match(/\$\s?\d+(?:\.\d+)?(?:\s*\/\s*(?:mo|month|year|yr))?/i)?.[0];
93 return price ? `Starts at ${price.replace(/\s+/g, " ")}` : "Paid plans";
94 }
95 if (/\b(paid|subscription|plan)\b/.test(text)) return "Paid plans";
96 return "Check vendor pricing";
97}
98
99function inferSetupTime(tool) {
100 const text = [tool.pricing, tool.deployment, tool.key_features, tool.cons]
101 .filter(Boolean)
102 .join(" ")
103 .toLowerCase();
104
105 if (/\b(self-hosted|open-source|api|developer)\b/.test(text)) return "15-20 minutes";
106 if (/\b(enterprise|integration|complex)\b/.test(text)) return "10-15 minutes";
107 return "5-10 minutes";
108}
109
110function pickAlternatives(toolName, categoryName, description) {
111 const text = `${categoryName || ""} ${description || ""}`.toLowerCase();
112 const mappings = [
113 { re: /\b(llm|assistant|chat|chatbot)\b/, options: ["ChatGPT", "Claude", "Perplexity"] },
114 { re: /\b(image|art|visual|design)\b/, options: ["Midjourney", "DALL·E 3", "Stable Diffusion"] },
115 { re: /\b(video|avatar|editing|subtitle)\b/, options: ["Runway", "Synthesia", "Descript"] },
116 { re: /\b(code|developer|programming|debug)\b/, options: ["GitHub Copilot", "Cursor", "Codeium"] },
117 { re: /\b(automation|workflow|agent|orchestration)\b/, options: ["Zapier", "Make", "n8n"] },
118 { re: /\b(marketing|copy|seo|campaign)\b/, options: ["Jasper", "Copy.ai", "Writesonic"] },
119 { re: /\b(presentation|slides|deck)\b/, options: ["Gamma", "Canva", "Beautiful.ai"] },
120 { re: /\b(meeting|transcri|notes)\b/, options: ["Otter.ai", "Fireflies.ai", "Notion AI"] },
121 { re: /\b(data|analytics|dashboard|bi)\b/, options: ["Tableau", "Power BI", "Looker Studio"] },
122 { re: /\b(search|research|knowledge)\b/, options: ["Perplexity", "You.com", "ChatGPT"] },
123 ];
124
125 const fallback = ["ChatGPT", "Claude", "Perplexity"];
126 const matched = mappings.find((m) => m.re.test(text))?.options || fallback;
127 const lowerName = (toolName || "").toLowerCase();
128 const unique = matched.filter((alt) => !lowerName.includes(alt.toLowerCase().replace(/[^\w]/g, "")));
129 return unique.slice(0, 3).length >= 2 ? unique.slice(0, 3) : fallback.slice(0, 3);
130}
131
132function generateOverview(tool, categoryName) {
133 const time = inferTimeEstimateMinutes(tool);
134 const useCase = inferPrimaryUseCase(tool, categoryName);
135 const features = toLines(tool.key_features);
136 const cons = toLines(tool.cons);
137
138 const hero_headline = `Use ${tool.name} to ${useCase} in ${time} minutes`;
139 const hero_subhead = features.length >= 2
140 ? `Start with one outcome, apply ${features[0].toLowerCase()}, then iterate with ${features[1].toLowerCase()} to get usable results quickly.`
141 : `Start with one clear goal, add your context, and iterate with short prompts to get usable output fast.`;
142
143 const best_for = features.length
144 ? `${cleanSentence(features[0], "Practical day-to-day AI tasks")} and related workflows`
145 : `${cleanSentence(tool.description, "Practical day-to-day AI tasks")}`;
146
147 const not_for = cons.length
148 ? cleanSentence(cons[0], "Teams that require guaranteed accuracy without manual verification")
149 : "Tasks that require guaranteed accuracy without manual verification";
150
151 const quick_verdict = {
152 best_for,
153 not_for,
154 setup_time: inferSetupTime(tool),
155 cost_to_start: deriveCostToStart(tool.pricing),
156 alternatives: pickAlternatives(tool.name, categoryName, tool.description),
157 };
158
159 return {
160 hero_headline,
161 hero_subhead,
162 hero_time_estimate_minutes: time,
163 quick_verdict,
164 };
165}
166
167async function main() {
168 const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL;
169 const serviceKey = process.env.SUPABASE_SERVICE_ROLE_KEY;
170
171 if (!supabaseUrl || !serviceKey) {
172 throw new Error("Missing NEXT_PUBLIC_SUPABASE_URL or SUPABASE_SERVICE_ROLE_KEY in .env");
173 }
174
175 const supabase = createClient(supabaseUrl, serviceKey, {
176 auth: { autoRefreshToken: false, persistSession: false },
177 });
178
179 const { data: categories, error: categoriesError } = await supabase
180 .from("categories")
181 .select("id,name");
182 if (categoriesError) throw new Error(`Failed to fetch categories: ${categoriesError.message}`);
183 const categoryById = new Map((categories || []).map((c) => [c.id, c.name]));
184
185 const { data: tools, error: toolsError } = await supabase
186 .from("tools")
187 .select("id,name,slug,description,long_description,url,pricing,key_features,pros,cons,primary_category_id,tutorial_enabled")
188 .order("id", { ascending: true });
189 if (toolsError) throw new Error(`Failed to fetch tools: ${toolsError.message}`);
190
191 const { data: overviews, error: overviewError } = await supabase
192 .from("tool_tutorial_overviews")
193 .select("tool_id");
194 if (overviewError) throw new Error(`Failed to fetch existing overviews: ${overviewError.message}`);
195
196 const existingOverviewIds = new Set((overviews || []).map((row) => row.tool_id));
197 const pending = (tools || []).filter((tool) => !existingOverviewIds.has(tool.id));
198
199 console.log(`Total tools: ${(tools || []).length}`);
200 console.log(`Existing overviews: ${existingOverviewIds.size}`);
201 console.log(`Pending inserts: ${pending.length}`);
202 console.log(`Batch size: ${BATCH_SIZE}`);
203
204 let inserted = 0;
205 let updated = 0;
206 let failed = 0;
207
208 for (let i = 0; i < pending.length; i += BATCH_SIZE) {
209 const batch = pending.slice(i, i + BATCH_SIZE);
210 const batchNum = Math.floor(i / BATCH_SIZE) + 1;
211 const batchTotal = Math.ceil(pending.length / BATCH_SIZE);
212 console.log(`\n[Batch ${batchNum}/${batchTotal}] Processing ${batch.length} tools...`);
213
214 await Promise.all(
215 batch.map(async (tool, idx) => {
216 const itemNum = i + idx + 1;
217 const label = `[${itemNum}/${pending.length}] ${tool.name} (id=${tool.id})`;
218 try {
219 const categoryName = categoryById.get(tool.primary_category_id) || null;
220 const overview = generateOverview(tool, categoryName);
221
222 const { error: insertError } = await supabase
223 .from("tool_tutorial_overviews")
224 .insert({
225 tool_id: tool.id,
226 hero_headline: overview.hero_headline,
227 hero_subhead: overview.hero_subhead,
228 hero_time_estimate_minutes: overview.hero_time_estimate_minutes,
229 quick_verdict: overview.quick_verdict,
230 });
231 if (insertError) throw new Error(`insert overview failed: ${insertError.message}`);
232
233 const { error: updateError } = await supabase
234 .from("tools")
235 .update({ tutorial_enabled: true })
236 .eq("id", tool.id);
237 if (updateError) throw new Error(`update tutorial_enabled failed: ${updateError.message}`);
238
239 inserted += 1;
240 updated += 1;
241 console.log(`${label} -> inserted + tutorial_enabled=true`);
242 } catch (error) {
243 failed += 1;
244 const message = error instanceof Error ? error.message : String(error);
245 console.error(`${label} -> FAILED: ${message}`);
246 }
247 })
248 );
249 }
250
251 console.log("\nDone.");
252 console.log(`Inserted overviews: ${inserted}`);
253 console.log(`Updated tools.tutorial_enabled: ${updated}`);
254 console.log(`Failures: ${failed}`);
255}
256
257main().catch((error) => {
258 console.error(`Fatal error: ${error.message}`);
259 process.exit(1);
260});