/** * Fetch AI greetings from api.usj.cc and write to static JS file. * Usage: node scripts/fetch_greetings.js * Env: RSS_API_TOKEN (same token used for RSS/links) */ const fs = require("fs"); const path = require("path"); const API_BASE = "https://api.usj.cc/api/ai/greeting"; let TOKEN = process.env.RSS_API_TOKEN; // Fallback: read from write/.env if (!TOKEN) { try { const envPath = path.join(__dirname, "..", "write", ".env"); const envContent = fs.readFileSync(envPath, "utf-8"); const match = envContent.match(/^RSS_API_TOKEN=(.+)$/m); if (match) TOKEN = match[1].trim(); } catch {} } if (!TOKEN) { console.error("RSS_API_TOKEN env var is required (or write/.env with RSS_API_TOKEN=xxx)"); process.exit(1); } async function main() { const url = `${API_BASE}?token=${encodeURIComponent(TOKEN)}`; const res = await fetch(url); if (!res.ok) { const body = await res.text(); throw new Error(`API returned ${res.status}: ${body}`); } const data = await res.json(); const greetings = data.greetings || []; const byTime = { morning: [], noon: [], afternoon: [], evening: [], night: [] }; const holidays = {}; const generic = []; const timeKeys = Object.keys(byTime); greetings.forEach((g) => { if (g.holiday) { holidays[g.holiday] = g.text; return; } var t = g.time || ""; // Normalize: strip "weekday-"/"weekend-" prefix, lowercase var bucket = t.replace(/^(weekday|weekend)-/, "").toLowerCase(); if (byTime[bucket]) { byTime[bucket].push(g.text); } else if (t === "weekend") { // "weekend" without a specific time → add to all slots timeKeys.forEach(function(k) { byTime[k].push(g.text); }); } else { generic.push(g.text); } }); // Keep all greetings per time slot (frontend picks randomly) var timeGreetings = {}; timeKeys.forEach(function(key) { var list = byTime[key]; if (list.length === 0) list = generic; if (list.length > 0) { timeGreetings[key] = list; } }); const js = "window.searchGreetings=" + JSON.stringify(timeGreetings) + ";window.searchHolidays=" + JSON.stringify(holidays) + ";"; const outDir = path.join(__dirname, "..", "static", "js"); fs.mkdirSync(outDir, { recursive: true }); const outPath = path.join(outDir, "ai_greetings.js"); fs.writeFileSync(outPath, js, "utf-8"); console.log( `Wrote ${Object.keys(timeGreetings).length} time slots, ${Object.keys(holidays).length} holidays → ${outPath}` ); } main().catch((e) => { console.error("Failed to fetch AI greetings:", e.message); process.exit(1); });