/**
 * CLI seeder — ingest PDFs into a tenant's knowledge base.
 *
 *   node scripts/ingest.js <admin_email> <file1.pdf> [file2.pdf ...]
 *
 * Most uploads happen from the dashboard; this is handy for bulk seeding.
 */
import "dotenv/config";
import fs from "node:fs";
import path from "node:path";
import { getTenantByEmail, ensureVectorStore, clientFor } from "../lib/tenants.js";
import { ingestPaths } from "../lib/knowledge.js";

const [email, ...files] = process.argv.slice(2);

async function main() {
  if (!email || !files.length) {
    console.error("Usage: node scripts/ingest.js <admin_email> <file.pdf> [...]");
    process.exit(1);
  }
  const tenant = await getTenantByEmail(email);
  if (!tenant) { console.error(`No tenant with admin email ${email}`); process.exit(1); }

  const paths = files.map((f) => path.resolve(f));
  const missing = paths.filter((p) => !fs.existsSync(p));
  if (missing.length) { console.error("Missing files:\n  " + missing.join("\n  ")); process.exit(1); }

  console.log(`Ingesting ${paths.length} file(s) into "${tenant.name}"…`);
  const vectorStoreId = await ensureVectorStore(tenant);
  const { batch } = await ingestPaths(clientFor(tenant), vectorStoreId, paths);
  console.log(`Done. Indexed ${batch.file_counts.completed}/${batch.file_counts.total}.`);
  process.exit(0);
}

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