#!/usr/bin/env node
/**
 * measure-launch-rate.mjs — first-party measurement of the Solana meme coin
 * launch rate, and the source of every "measured" figure in
 * /blog/how-many-meme-coins-are-created-every-day.
 *
 * Two independent measurements, because they answer different questions:
 *
 *   1. `pumpfun` — paginates pump.fun's public coin listing, newest first, and
 *      reconstructs a contiguous census of everything that venue minted in the
 *      last ~45 minutes. Gives the rate, the creator distribution, the market-cap
 *      distribution and the graduation rate for one cohort.
 *
 *   2. `chain` — polls Jupiter's recent-token endpoint on a loop and accumulates
 *      unique mints across every launchpad it indexes. Gives the chain-wide rate,
 *      the per-launchpad split, and (via `audit.devMints`) each creator's LIFETIME
 *      mint count rather than just what they did inside our window.
 *
 * ---------------------------------------------------------------------------
 * THE PAGE-SIZE TRAP — read this before changing PAGE_SIZE.
 *
 * pump.fun's listing accepts `limit` but caps the response at 70 rows. Ask for
 * `limit=100` and you get 70. The obvious loop — offset += 100 — therefore skips
 * rows 70-99 of every page and silently drops ~30% of all launches, which
 * understates the launch rate by the same 30%. We shipped that error once. The
 * offsets below step by the ACTUAL page size, and `verifyContiguity` fails loudly
 * if consecutive pages ever overlap or leave a gap.
 * ---------------------------------------------------------------------------
 *
 * Usage:
 *   node scripts/seo/measure-launch-rate.mjs pumpfun
 *   node scripts/seo/measure-launch-rate.mjs chain [minutes]
 *   node scripts/seo/measure-launch-rate.mjs pumpfun --json > sample.json
 *
 * No API key, no auth, no paid tier. Every endpoint is public.
 */

const PUMP_LISTING = "https://frontend-api-v3.pump.fun/coins";
const JUP_RECENT = "https://lite-api.jup.ag/tokens/v2/recent";
const DEFILLAMA_SOL =
	"https://coins.llama.fi/prices/current/solana:So11111111111111111111111111111111111111112";

/** Server-enforced rows per response. See THE PAGE-SIZE TRAP above. */
const PAGE_SIZE = 70;
/** The listing stops returning rows past ~1,050; deeper offsets come back empty. */
const MAX_OFFSET = 1400;
const HEADERS = { "User-Agent": "alchemii-launch-census", Accept: "application/json" };

const sleep = (ms) => new Promise((r) => setTimeout(r, ms));

async function getJson(url) {
	const res = await fetch(url, { headers: HEADERS });
	if (!res.ok) throw new Error(`${res.status} ${res.statusText} for ${url}`);
	return res.json();
}

async function solPrice() {
	const key = "solana:So11111111111111111111111111111111111111112";
	const data = await getJson(DEFILLAMA_SOL);
	return data.coins[key].price;
}

/** Pulls the listing page by page until it runs dry, deduped by mint. */
async function collectPumpFun() {
	const byMint = new Map();
	const pages = [];
	for (let offset = 0; offset <= MAX_OFFSET; offset += PAGE_SIZE) {
		const url = `${PUMP_LISTING}?offset=${offset}&limit=${PAGE_SIZE}&sort=created_timestamp&order=DESC&includeNsfw=true`;
		const page = await getJson(url);
		if (!page.length) break;
		pages.push(page);
		for (const coin of page) byMint.set(coin.mint, coin);
		await sleep(300);
	}
	return { coins: [...byMint.values()], pages };
}

/**
 * Consecutive pages must abut: the newest row of page N+1 immediately precedes
 * the oldest row of page N, with no time gap between them.
 *
 * A small overlap is expected and harmless. New coins are minted while we
 * paginate, which pushes every row down by one, so a page fetched a second later
 * can repeat one or two mints from the page before it. Deduping by mint absorbs
 * that. What must never happen is a GAP — a stretch of time neither page covers
 * — because that is the signature of stepping by more than the true page size,
 * and it silently deflates every rate in the report.
 */
const DRIFT_TOLERANCE = 5;

function verifyContiguity(pages) {
	const problems = [];
	for (let i = 1; i < pages.length; i++) {
		const prev = pages[i - 1];
		const cur = pages[i];
		const overlap = new Set(cur.map((c) => c.mint)).intersection(
			new Set(prev.map((c) => c.mint)),
		);
		if (overlap.size > DRIFT_TOLERANCE) {
			problems.push(
				`pages ${i - 1}/${i} share ${overlap.size} mints — more than live-insertion drift explains`,
			);
		}
		const oldestPrev = Math.min(...prev.map((c) => c.created_timestamp));
		const newestCur = Math.max(...cur.map((c) => c.created_timestamp));
		// Overlap means newestCur >= oldestPrev, which is fine. A gap means the
		// next page starts strictly older than where the previous one ended.
		if (!overlap.size && newestCur < oldestPrev - 1000) {
			const gapSec = Math.round((oldestPrev - newestCur) / 1000);
			problems.push(
				`pages ${i - 1}/${i} leave a ${gapSec}s hole — PAGE_SIZE is smaller than the server's real page`,
			);
		}
	}
	return problems;
}

function quantile(sorted, q) {
	if (!sorted.length) return 0;
	const i = Math.min(sorted.length - 1, Math.max(0, Math.round(q * (sorted.length - 1))));
	return sorted[i];
}

function reportPumpFun(coins, price) {
	const sorted = [...coins].sort((a, b) => a.created_timestamp - b.created_timestamp);
	const t0 = sorted[0].created_timestamp / 1000;
	const t1 = sorted.at(-1).created_timestamp / 1000;
	const spanMin = (t1 - t0) / 60;
	const perMin = coins.length / spanMin;

	const byCreator = new Map();
	for (const c of sorted) byCreator.set(c.creator, (byCreator.get(c.creator) ?? 0) + 1);
	const counts = [...byCreator.values()];
	const oneOff = counts.filter((v) => v === 1).length;

	// Market caps are compared in USD: a minority of coins are quoted in USDC
	// rather than SOL, so market_cap_quote is not a single unit across the set.
	const caps = sorted.map((c) => c.usd_market_cap ?? 0).sort((a, b) => a - b);
	const startCap = 27.96 * price; // 1B tokens against the 30 vSOL / 1.073B vToken init
	const gradCap = 410 * price;
	const share = (fn) => (sorted.filter(fn).length / sorted.length) * 100;

	// Tokens minted early in the window have had time to graduate; ones minted at
	// the end have not. Restricting to a minimum age is the honest denominator.
	const matured = sorted.filter((c) => (t1 - c.created_timestamp / 1000) / 60 >= 20);

	console.log(`\npump.fun census — ${new Date(t0 * 1000).toISOString()} to ${new Date(t1 * 1000).toISOString()}`);
	console.log(`  SOL price used              $${price.toFixed(2)}`);
	console.log(`  tokens                      ${coins.length} over ${spanMin.toFixed(2)} min`);
	console.log(`  launches / minute           ${perMin.toFixed(2)}`);
	console.log(`  launches / hour             ${Math.round(perMin * 60)}`);
	console.log(`  launches / day (pace)       ${Math.round(perMin * 1440)}`);
	console.log(`  distinct creator wallets    ${byCreator.size}`);
	console.log(`  wallets launching once      ${oneOff} (${((oneOff / byCreator.size) * 100).toFixed(1)}%)`);
	console.log(`  busiest wallet              ${Math.max(...counts)} launches in window`);
	console.log(`  median market cap           $${quantile(caps, 0.5).toFixed(0)} (curve start = $${startCap.toFixed(0)})`);
	console.log(`  above the curve start       ${share((c) => (c.usd_market_cap ?? 0) >= startCap * 1.003).toFixed(2)}%`);
	console.log(`  reached graduation cap      ${share((c) => (c.usd_market_cap ?? 0) >= gradCap).toFixed(2)}%`);
	console.log(`  curve complete (all)        ${share((c) => c.complete).toFixed(2)}%`);
	console.log(`  curve complete (20min+ old) ${((matured.filter((c) => c.complete).length / matured.length) * 100).toFixed(2)}%  n=${matured.length}`);
	console.log(`  shipped with a description  ${share((c) => (c.description ?? "").trim()).toFixed(1)}%`);
}

async function runPumpFun(asJson) {
	const [{ coins, pages }, price] = await Promise.all([collectPumpFun(), solPrice()]);
	if (asJson) {
		process.stdout.write(JSON.stringify({ price, coins }, null, 2));
		return;
	}
	const problems = verifyContiguity(pages);
	if (problems.length) {
		console.error("\nCONTIGUITY CHECK FAILED — rates below are not trustworthy:");
		for (const p of problems) console.error(`  - ${p}`);
		process.exitCode = 1;
	} else {
		console.log(`\ncontiguity check: ${pages.length} pages abut exactly, no overlap, no gap`);
	}
	reportPumpFun(coins, price);
}

async function runChain(minutes) {
	const byMint = new Map();
	const until = Date.now() + minutes * 60_000;
	let polls = 0;
	while (Date.now() < until) {
		try {
			for (const t of await getJson(JUP_RECENT)) {
				if (!byMint.has(t.id)) byMint.set(t.id, t);
			}
			polls++;
		} catch {
			// A dropped poll costs coverage, not correctness — the next one
			// re-reads the same feed. Only a gap longer than the feed's own
			// depth would lose mints, which is why the interval is 20s.
		}
		await sleep(20_000);
	}
	const tokens = [...byMint.values()].filter((t) => t.firstPool?.createdAt);
	const times = tokens.map((t) => Date.parse(t.firstPool.createdAt)).sort((a, b) => a - b);
	const spanMin = (times.at(-1) - times[0]) / 60_000;

	const byPad = new Map();
	for (const t of tokens) {
		const pad = t.launchpad ?? "(unattributed)";
		byPad.set(pad, (byPad.get(pad) ?? 0) + 1);
	}
	const devMints = tokens
		.map((t) => t.audit?.devMints ?? 0)
		.sort((a, b) => a - b);
	const pct = (fn) => ((tokens.filter(fn).length / tokens.length) * 100).toFixed(1);

	console.log(`\nchain-wide census — ${polls} polls over ${minutes} min`);
	console.log(`  tokens                      ${tokens.length} across ${spanMin.toFixed(1)} min`);
	console.log(`  launches / minute           ${(tokens.length / spanMin).toFixed(2)}`);
	console.log(`  launches / day (pace)       ${Math.round((tokens.length / spanMin) * 1440)}`);
	console.log("  launchpad split:");
	for (const [pad, n] of [...byPad].sort((a, b) => b[1] - a[1])) {
		console.log(`    ${pad.padEnd(26)} ${String(n).padStart(5)}  ${((n / tokens.length) * 100).toFixed(1)}%`);
	}
	console.log(`  creator's LIFETIME mints — median ${quantile(devMints, 0.5)}, p90 ${quantile(devMints, 0.9)}`);
	console.log(`    from a wallet that has minted 2+   ${pct((t) => (t.audit?.devMints ?? 0) >= 2)}%`);
	console.log(`    from a wallet that has minted 10+  ${pct((t) => (t.audit?.devMints ?? 0) >= 10)}%`);
	console.log(`    from a wallet that has minted 100+ ${pct((t) => (t.audit?.devMints ?? 0) >= 100)}%`);
	console.log(`  linked an X account         ${pct((t) => t.twitter)}%`);
	console.log(`  linked a website            ${pct((t) => t.website)}%`);
}

const [mode = "pumpfun", arg] = process.argv.slice(2);
if (mode === "chain") await runChain(Number(arg) || 30);
else await runPumpFun(process.argv.includes("--json"));
