#!/bin/sh
# Rebuild data/pages.json from live wiki trending data (needs the adom-wiki CLI).
set -e
DIR="$(cd "$(dirname "$(readlink -f "$0")")" && pwd)"
adom-wiki page trending --json > /tmp/hero-studio-trending.json
node -e '
const fs = require("fs");
const d = JSON.parse(fs.readFileSync("/tmp/hero-studio-trending.json", "utf8"));
const clean = (s) => (s || "").replace(/—/g, ",").replace(/–/g, "-").trim();
const out = d.data.pages.map((p) => ({
  owner: p.owner, slug: p.slug, type: p.type,
  title: clean(p.title || p.slug),
  author: p.author_name || p.owner,
  score: p.composite_score || 0,
  stars: p.star_count || 0,
  installs30d: p.install_count_30d || 0,
  brief: clean(p.brief).slice(0, 220),
  tags: (() => { try { return JSON.parse(p.tags || "[]").slice(0, 4); } catch { return []; } })(),
  updated_at: p.updated_at,
}));
fs.writeFileSync(process.argv[1] + "/data/pages.json", JSON.stringify(out, null, 1));
console.log("wrote " + out.length + " pages");
' "$DIR"
rm -f /tmp/hero-studio-trending.json
echo "OK: data refreshed, restart the server to pick it up"