#!/usr/bin/env tsx
/**
 * CLI: submit URLs to IndexNow.
 *
 * Usage:
 *   # Submit specific URLs
 *   pnpm tsx scripts/indexnow-submit.ts https://www.elevaseo.com/page-a https://www.elevaseo.com/page-b
 *
 *   # Submit every URL from the live sitemap (use post-deploy)
 *   pnpm tsx scripts/indexnow-submit.ts --all
 *
 *   # Dry-run: print payload without sending
 *   pnpm tsx scripts/indexnow-submit.ts --dry-run --all
 */

import { submitToIndexNow } from "@/lib/indexnow";

const SITEMAP_URL = "https://www.elevaseo.com/sitemap.xml";

async function readSitemapUrls(): Promise<string[]> {
  const response = await fetch(SITEMAP_URL, {
    headers: { "User-Agent": "indexnow-submit/1.0" },
  });
  if (!response.ok) {
    throw new Error(`Sitemap fetch failed: ${response.status}`);
  }
  const xml = await response.text();
  // Cheap parse: regex extract <loc>...</loc>. The sitemap is well-formed XML
  // generated by Next.js so we don't need a full parser.
  return Array.from(xml.matchAll(/<loc>([^<]+)<\/loc>/g)).map((m) => m[1]);
}

async function main() {
  const args = process.argv.slice(2);
  const dryRun = args.includes("--dry-run");
  const submitAll = args.includes("--all");
  const explicitUrls = args.filter((arg) => arg.startsWith("https://"));

  let urls: string[];
  if (submitAll) {
    console.log(`Reading sitemap: ${SITEMAP_URL}`);
    urls = await readSitemapUrls();
    console.log(`Found ${urls.length} URLs.`);
  } else if (explicitUrls.length > 0) {
    urls = explicitUrls;
  } else {
    console.error(
      "Usage: pnpm tsx scripts/indexnow-submit.ts <url> [<url> ...] | --all [--dry-run]"
    );
    process.exit(1);
  }

  if (dryRun) {
    console.log("\nDry run. URLs that would be submitted:");
    for (const url of urls) {
      console.log(`  ${url}`);
    }
    return;
  }

  const result = await submitToIndexNow(urls);
  console.log(
    `\nIndexNow: submitted=${result.submittedCount} rejected=${result.rejectedCount} batches=${result.batches.length}`
  );
  for (const batch of result.batches) {
    console.log(
      `  batch ${batch.batchSize}: HTTP ${batch.status} ${batch.statusText}`
    );
  }

  if (!result.ok) {
    // 400 Bad Request, 403 Key mismatch, 422 Invalid URLs, 429 Rate limit
    process.exit(1);
  }
}

main().catch((err) => {
  console.error(err);
  process.exit(1);
});
