import fs from 'fs'; import path from 'path'; import dotenv from 'dotenv'; import { createClient } from '@supabase/supabase-js'; dotenv.config({ path: '.env' }); const VERIFIED_DATE = '2026-02-18'; const GENERIC_TOOL_ID = 673; // OpenAI Chat GPT (fallback because tool_id is NOT NULL in live schema) const SOURCE_FILE = '/tmp/prompt_repos/ChatGPT-Shortcut/src/data/prompt_en.json'; const OUTPUT_REPORT = '/tmp/popular-prompts-report.md'; const OUTPUT_JSON = '/tmp/popular-prompts.json'; if (!process.env.NEXT_PUBLIC_SUPABASE_URL || !process.env.SUPABASE_SERVICE_ROLE_KEY) { throw new Error('Missing Supabase environment variables in .env'); } if (!fs.existsSync(SOURCE_FILE)) { throw new Error(`Missing source file: ${SOURCE_FILE}`); } const supabase = createClient(process.env.NEXT_PUBLIC_SUPABASE_URL, process.env.SUPABASE_SERVICE_ROLE_KEY); const raw = JSON.parse(fs.readFileSync(SOURCE_FILE, 'utf8')); const badPattern = /(jailbreak|dan|unrestricted|succubus|erotic|sexual|boyfriend|girlfriend|evil|hacker|hypnot|dream|fortune|tarot|astrolog|linux terminal|midjourney|stable diffusion|image unlocker|game|chess|spongebob|magician|comedian|rapper|novelist|poet|rpg|actor|character|drunk|translator\s*\(|friend's advice|gaslighter|relationship|psychologist|yogi|makeup|dietitian|personal stylist|tea-taster|mechanic|dentist|doctor|hypnotherapist|pet behaviorist|car navigation|chemical reaction vessel|dall-e|art advisor|film critic|food critic|tech reviewer|journal reviewer|interior decorator|travel itinerary)/i; const usefulPattern = /(write|writer|email|summary|title|translate|translator|essay|journal|cover letter|report|note|research|review|code|developer|sql|frontend|architect|product manager|startup|advertiser|sales|social media|rephrase|seo|faq|tester|regex|commit|customer service|financial|accountant|statistic|analysis|analyst|fallacy|educational|teacher|resume|pitch|business|plan|strategy|marketing|meeting|task|brainstorm|copy)/i; function normalizeWhitespace(s) { return (s || '').replace(/\s+/g, ' ').trim(); } function textOf(item) { return normalizeWhitespace(`${item?.en?.title || ''} ${item?.en?.prompt || ''} ${(item?.tags || []).join(' ')}`.toLowerCase()); } function categoryOf(item) { const t = textOf(item); if (/(code|developer|sql|regex|commit message|python|javascript|frontend|architect|tester|solr|vue|machine learning|algorithm|debug|interpreter)/.test(t)) return 'coding'; if (/(seo|advertiser|social media|influencer|sales|faq|copy|campaign|brand|marketing|domain generator)/.test(t)) return 'marketing'; if (/(product manager|ceo|startup|recruiter|talent|customer service|legal advisor|accountant|financial analyst|business|position interviewer|resume|stakeholder)/.test(t)) return 'business'; if (/(note-taking|weekly report|process document|material collection|teacher|classroom|worksheet|meeting|task|plan|checklist|organize|productivity)/.test(t)) return 'productivity'; if (/(story|title generator|aphorism|creative|script|journalist|essay writer|brainstorm|naming|tone|voice)/.test(t)) return 'creative'; if (/(analysis|analyst|fallacy|statistic|summary|research|conceptual|feynman|think tank|core summary|confusion query|deep thinking|compare|evaluate)/.test(t)) return 'analysis'; return 'writing'; } function sanitizeTitle(title) { return normalizeWhitespace((title || 'Untitled Prompt') .replace(/[①②③④⑤⑥⑦⑧⑨⑩]/g, '') .replace(/\s+/g, ' ') .trim()); } function extractVariables(prompt, category) { const vars = new Set(); const p = prompt || ''; for (const m of p.matchAll(/\[([^\]\n]{1,40})\]/g)) vars.add(m[1]); for (const m of p.matchAll(/\$\{([^}:\n]{1,40})(?::[^}]*)?\}/g)) vars.add(m[1]); for (const m of p.matchAll(/<([a-zA-Z][^>\n]{1,40})>/g)) vars.add(m[1]); const cleaned = [...vars] .map((v) => v.toLowerCase().replace(/[^a-z0-9]+/g, '_').replace(/^_+|_+$/g, '')) .filter((v) => v && v.length <= 32) .slice(0, 4); if (cleaned.length > 0) { return Object.fromEntries(cleaned.map((k) => [k, 'string'])); } const defaults = { writing: { draft_text: 'string', target_tone: 'string' }, coding: { code_snippet: 'string', issue: 'string' }, analysis: { input_text: 'string', objective: 'string' }, marketing: { product: 'string', audience: 'string' }, productivity: { notes: 'string', goal: 'string' }, creative: { topic: 'string', style: 'string' }, business: { business_context: 'string', objective: 'string' }, }; return defaults[category] || { input_text: 'string' }; } function sampleInputFor(category, vars) { const seed = { draft_text: 'We need to send the update later today. Keep it short.', target_tone: 'professional', code_snippet: 'SELECT * FROM orders WHERE DATE(created_at)=CURRENT_DATE;', issue: 'query is slow on large tables', input_text: 'Q4 churn increased from 4.1% to 5.3%. Main reasons: onboarding delays and support backlog.', objective: 'identify top actions for the next 30 days', product: 'project management SaaS for small teams', audience: 'operations managers at startups', notes: 'Finalize launch plan, assign owners, and confirm deadlines.', goal: 'publish launch checklist by Friday', topic: 'remote onboarding', style: 'clear and practical', business_context: 'B2B SaaS with rising acquisition costs', }; const parts = Object.keys(vars).map((k) => `${k}=${seed[k] || 'example input'}`); if (parts.length > 0) return parts.join('; '); const fallback = { writing: 'draft_text=Please review this email and improve clarity.', coding: 'code_snippet=function sum(a,b){return a-b}; issue=wrong output', analysis: 'input_text=Survey feedback from 500 users; objective=find top pain points', marketing: 'product=AI note app; audience=college students', productivity: 'notes=Weekly planning notes; goal=ship two features', creative: 'topic=city commute; style=short narrative', business: 'business_context=subscription plateau; objective=raise retention', }; return fallback[category] || 'input_text=example'; } function sampleOutputFor(category) { const outputs = { writing: 'Rewritten message with clearer structure, concise wording, and a direct call to action.', coding: 'Root-cause summary, fixed code snippet, and short test checklist to confirm behavior.', analysis: 'Structured findings with key patterns, risks, and ranked recommendations.', marketing: 'Campaign draft with audience-specific message, channel plan, and success metrics.', productivity: 'Action plan with priorities, owners, deadlines, and next review date.', creative: 'Original draft with a clear voice, vivid details, and a consistent style.', business: 'Decision brief with options, tradeoffs, financial impact, and recommended next step.', }; return outputs[category] || 'Structured response with clear next steps.'; } function attributionFor(sourceUrl) { if (!sourceUrl) return 'ChatGPT Shortcut community'; if (/github\.com\/f\//i.test(sourceUrl)) return 'f/awesome-chatgpt-prompts'; if (/github\.com\/rockbenben\/ChatGPT-Shortcut/i.test(sourceUrl)) return 'rockbenben/ChatGPT-Shortcut'; if (/learnprompting\.org/i.test(sourceUrl)) return 'Learn Prompting'; if (/aleydasolis\.com/i.test(sourceUrl)) return 'Aleyda Solis'; if (/platform\.openai\.com/i.test(sourceUrl)) return 'OpenAI examples'; if (/playpcesor\.com/i.test(sourceUrl)) return 'PlayPCesor'; return new URL(sourceUrl).hostname.replace(/^www\./, ''); } function tagify(item, category, difficulty) { const existing = (item.tags || []) .map((t) => String(t).toLowerCase().replace(/[^a-z0-9]+/g, '-').replace(/^-+|-+$/g, '')) .filter(Boolean); const titleTerms = sanitizeTitle(item.en?.title || '') .toLowerCase() .split(/[^a-z0-9]+/) .filter((x) => x.length > 3) .slice(0, 2) .map((x) => x.replace(/[^a-z0-9]+/g, '')); const merged = [category, difficulty, ...existing, ...titleTerms] .filter(Boolean) .filter((v, i, a) => a.indexOf(v) === i) .slice(0, 5); while (merged.length < 3) merged.push('popular'); return merged; } function complexityScore(promptText) { const p = (promptText || '').toLowerCase(); const indicators = ['step by step', 'table', 'criteria', 'constraints', 'checklist', 'evaluate', 'compare', 'edge case', 'format']; const indicatorHits = indicators.reduce((n, key) => n + (p.includes(key) ? 1 : 0), 0); return (promptText.length / 220) + indicatorHits; } const candidates = raw .filter((item) => { const body = textOf(item); const prompt = normalizeWhitespace(item?.en?.prompt || ''); return prompt.length >= 80 && !badPattern.test(body) && usefulPattern.test(body); }) .map((item) => ({ ...item, title: sanitizeTitle(item.en?.title || ''), prompt: normalizeWhitespace(item.en?.prompt || ''), category: categoryOf(item), score: (item.weight || 0) + (item.website ? 150 : 0), })) .sort((a, b) => b.score - a.score); const categoryTargets = { writing: 16, coding: 16, analysis: 14, marketing: 14, productivity: 14, creative: 10, business: 16, }; const selected = []; const usedIds = new Set(); for (const [category, target] of Object.entries(categoryTargets)) { const bucket = candidates.filter((c) => c.category === category && !usedIds.has(c.id)).slice(0, target); for (const item of bucket) { selected.push(item); usedIds.add(item.id); } } for (const item of candidates) { if (selected.length >= 100) break; if (usedIds.has(item.id)) continue; selected.push(item); usedIds.add(item.id); } if (selected.length < 100) { throw new Error(`Only selected ${selected.length} prompts; expected 100`); } const final100 = selected.slice(0, 100); const byComplexity = [...final100].sort((a, b) => complexityScore(a.prompt) - complexityScore(b.prompt)); const difficultyMap = new Map(); byComplexity.forEach((item, i) => { const difficulty = i < 30 ? 'beginner' : i < 70 ? 'intermediate' : 'advanced'; difficultyMap.set(item.id, difficulty); }); const records = final100.map((item, idx) => { const difficulty = difficultyMap.get(item.id) || 'intermediate'; const variables = extractVariables(item.prompt, item.category); const source = item.website || 'https://github.com/rockbenben/ChatGPT-Shortcut/blob/main/src/data/prompt_en.json'; return { tool_id: GENERIC_TOOL_ID, template_order: 101 + idx, title: item.title, category_tag: item.category, tags: tagify(item, item.category, difficulty), prompt_text: item.prompt, variables, sample_input: sampleInputFor(item.category, variables), sample_output: sampleOutputFor(item.category), difficulty, metadata: { source, attribution: attributionFor(source), verified: VERIFIED_DATE, popularity_weight: item.weight || 0, source_prompt_id: item.id, }, }; }); const categoryBreakdown = records.reduce((acc, r) => { acc[r.category_tag] = (acc[r.category_tag] || 0) + 1; return acc; }, {}); const difficultyBreakdown = records.reduce((acc, r) => { acc[r.difficulty] = (acc[r.difficulty] || 0) + 1; return acc; }, {}); const sourceSet = [...new Set(records.map((r) => r.metadata.source))]; const researchSources = [ 'https://github.com/f/prompts.chat', 'https://github.com/f/prompts.chat/blob/main/prompts.csv', 'https://github.com/rockbenben/ChatGPT-Shortcut', 'https://github.com/rockbenben/ChatGPT-Shortcut/blob/main/src/data/prompt_en.json', 'https://github.com/awesome-chatgpt-prompts/awesome-chatgpt-prompts', 'https://github.com/ai-boost/awesome-prompts', 'https://github.com/dair-ai/Prompt-Engineering-Guide', 'https://www.promptingguide.ai/', 'https://github.com/brexhq/prompt-engineering', 'https://platform.openai.com/examples', 'https://www.aleydasolis.com/en/search-engine-optimization/chatgpt-for-seo/', 'https://www.playpcesor.com/2023/03/chatgpt-2.html', 'https://prompthero.com/', 'https://promptbase.com/', 'https://flowgpt.com/', 'https://sharegpt.com/', 'https://www.promptperfect.xyz/', 'https://www.reddit.com/r/ChatGPT/', 'https://www.reddit.com/r/ClaudeAI/', 'https://www.reddit.com/r/PromptEngineering/', 'https://x.com/rowancheung', 'https://x.com/heykahn', 'https://x.com/bentossell', 'https://x.com/levelsio', 'https://x.com/search?q=%23ChatGPTPrompts', ]; const lines = []; lines.push('# AIRP Popular Prompts Report'); lines.push(''); lines.push(`- Verified date: ${VERIFIED_DATE}`); lines.push(`- Candidate pool size: ${candidates.length}`); lines.push(`- Final selected prompts: ${records.length}`); lines.push(`- Unique prompt source URLs used: ${sourceSet.length}`); lines.push(''); lines.push('## Category Breakdown'); for (const [k, v] of Object.entries(categoryBreakdown)) lines.push(`- ${k}: ${v}`); lines.push(''); lines.push('## Difficulty Breakdown'); for (const [k, v] of Object.entries(difficultyBreakdown)) lines.push(`- ${k}: ${v}`); lines.push(''); lines.push('## Research Sources (20-30)'); for (const s of researchSources) lines.push(`- ${s}`); lines.push(''); lines.push('## Prompt Records (101-200)'); for (const r of records) { lines.push(`- ${r.template_order}. ${r.title} | ${r.category_tag} | ${r.difficulty} | ${r.metadata.source}`); } lines.push(''); // Replace any existing rows in this range for the selected fallback tool. const deleteRes = await supabase .from('tool_prompt_templates') .delete() .eq('tool_id', GENERIC_TOOL_ID) .gte('template_order', 101) .lte('template_order', 200); if (deleteRes.error) throw new Error(`Delete failed: ${deleteRes.error.message}`); const chunkSize = 25; let inserted = 0; for (let i = 0; i < records.length; i += chunkSize) { const chunk = records.slice(i, i + chunkSize); const ins = await supabase.from('tool_prompt_templates').insert(chunk).select('id'); if (ins.error) throw new Error(`Insert failed at chunk ${i / chunkSize + 1}: ${ins.error.message}`); inserted += ins.data.length; } const verify = await supabase .from('tool_prompt_templates') .select('id,template_order,title,category_tag,difficulty', { count: 'exact' }) .eq('tool_id', GENERIC_TOOL_ID) .gte('template_order', 101) .lte('template_order', 200) .order('template_order'); if (verify.error) throw new Error(`Verification query failed: ${verify.error.message}`); lines.push('## Insertion Status'); lines.push(`- Deleted existing rows in range: yes`); lines.push(`- Insert attempted: ${records.length}`); lines.push(`- Insert returned IDs: ${inserted}`); lines.push(`- tool_id used: ${GENERIC_TOOL_ID} (schema requires NOT NULL)`); lines.push(`- Rows found after insert (tool_id=${GENERIC_TOOL_ID}, 101-200): ${verify.count}`); lines.push(`- Status: ${verify.count === 100 ? 'success' : 'mismatch'}`); fs.writeFileSync(OUTPUT_REPORT, lines.join('\n')); fs.writeFileSync(OUTPUT_JSON, JSON.stringify(records, null, 2)); console.log(JSON.stringify({ success: verify.count === 100, selected: records.length, inserted, verify_count: verify.count, category_breakdown: categoryBreakdown, difficulty_breakdown: difficultyBreakdown, report: OUTPUT_REPORT, json: OUTPUT_JSON, }, null, 2));