#!/usr/bin/env node
// scripts/seed-silver-vectors.js — DEPRECATED.
//
// This script was for the OpenAI File Search / vector store flow used by the
// previous version of silverAgent.js. We've moved to Anthropic Claude, which
// has no managed vector store — instead, lib/silverAgent.js inlines all 30
// transcripts + FAQ directly into the Claude system prompt with prompt
// caching (cache_control: ephemeral), so the corpus is billed at cache-hit
// rate after the first request. No separate seeding step required.
//
// The dry-run mode is preserved since it's still useful for validating that
// transcripts exist and aren't all stubs:
//
//   node scripts/seed-silver-vectors.js --dry-run
//
// Real-seed mode is left in place but disabled by default — pass --i-know
// if you really want to run it (e.g. if you bring back the OpenAI path).

import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { existsSync, readdirSync, readFileSync, writeFileSync, statSync } from 'fs';

const __filename = fileURLToPath(import.meta.url);
const SCRIPT_DIR = dirname(dirname(__filename));
const KEY = process.env.OPENAI_KEY;
const DRY_RUN = process.argv.includes('--dry-run') || !process.argv.includes('--i-know');

if (!KEY && !DRY_RUN) {
  console.error('OPENAI_KEY required (and pass --i-know to override the deprecation guard).');
  process.exit(1);
}

async function api(path, opts = {}) {
  const res = await fetch(`https://api.openai.com/v1${path}`, {
    ...opts,
    headers: {
      'Authorization': `Bearer ${KEY}`,
      ...(opts.headers || {}),
    },
  });
  if (!res.ok) {
    throw new Error(`${opts.method || 'GET'} ${path} → ${res.status} ${await res.text()}`);
  }
  return res.json();
}

function gatherFiles() {
  const out = [];
  const trDir = join(SCRIPT_DIR, 'data', 'silver', 'transcripts');
  const tplDir = join(SCRIPT_DIR, 'data', 'silver', 'templates');
  if (existsSync(trDir)) {
    for (const f of readdirSync(trDir)) {
      if (f.endsWith('.txt')) out.push(join(trDir, f));
    }
  }
  if (existsSync(tplDir)) {
    for (const f of readdirSync(tplDir)) {
      if (/\.(md|txt)$/.test(f)) out.push(join(tplDir, f));
    }
  }
  const faq = join(SCRIPT_DIR, 'data', 'silver', 'faq.md');
  if (existsSync(faq)) out.push(faq);
  return out;
}

async function uploadFile(path) {
  const buf = readFileSync(path);
  const fd = new FormData();
  fd.append('purpose', 'assistants');
  fd.append('file', new Blob([buf]), path.split('/').pop());
  const res = await fetch('https://api.openai.com/v1/files', {
    method: 'POST',
    headers: { 'Authorization': `Bearer ${KEY}` },
    body: fd,
  });
  if (!res.ok) throw new Error(`upload ${path} → ${res.status} ${await res.text()}`);
  const j = await res.json();
  return j.id;
}

async function main() {
  const files = gatherFiles();
  if (files.length === 0) {
    console.error('No source files found in data/silver/{transcripts,templates}/ or data/silver/faq.md');
    process.exit(1);
  }
  if (DRY_RUN) {
    console.log(`Would upload ${files.length} files:`);
    let stubCount = 0;
    for (const f of files) {
      const head = readFileSync(f, 'utf8').slice(0, 80).split('\n')[0];
      const isStub = head.includes('[STUB');
      if (isStub) stubCount += 1;
      console.log(`  ${isStub ? '[STUB] ' : '       '}${f}`);
    }
    console.log(`\n${files.length} total, ${stubCount} stubs (will be replaced with Whisper transcripts later).`);
    console.log('Re-run without --dry-run and with OPENAI_KEY set to actually seed the vector store.');
    return;
  }
  console.log(`Uploading ${files.length} files…`);
  const fileIds = [];
  for (const f of files) {
    const id = await uploadFile(f);
    console.log(`  ${f} → ${id}`);
    fileIds.push(id);
  }

  const store = await api('/vector_stores', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ name: `silver-course-${Date.now()}` }),
  });
  console.log(`Vector store: ${store.id}`);

  for (const fileId of fileIds) {
    await api(`/vector_stores/${store.id}/files`, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ file_id: fileId }),
    });
  }

  const out = join(SCRIPT_DIR, 'data', 'silver', '.vector-store-id');
  writeFileSync(out, store.id);
  console.log(`\nWrote ${out} → ${store.id}`);
  console.log('Set OPENAI_VECTOR_STORE_ID env var (or rely on the file) and you are good.');
}

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