/**
 * regen-cvmaster.js — Regenerate cvmaster.json for a specific mentee
 * Usage: node regen-cvmaster.js <slug>
 */

import 'dotenv/config';
import { dirname } from 'path';
import { fileURLToPath } from 'url';
import { generateCvMaster } from './lib/groupCvmaster.js';

const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));
const BOT_DIR    = `${SCRIPT_DIR}/bots/351923199040`;
const slug       = process.argv[2];

if (!slug) { console.error('Usage: node regen-cvmaster.js <slug>'); process.exit(1); }

// Anthropic Messages API. Maps the legacy 'gpt-4.1' default to Sonnet.
const MODEL_MAP = { 'gpt-4.1': 'claude-sonnet-4-5', 'gpt-4.1-mini': 'claude-haiku-4-5' };
async function ai(system, messages, model = 'gpt-4.1') {
  const claudeModel = model.startsWith('claude-') ? model : (MODEL_MAP[model] || 'claude-sonnet-4-5');
  const cleanMessages = (messages || [])
    .filter(m => m.role === 'user' || m.role === 'assistant')
    .map(m => ({ role: m.role, content: m.content }));
  const res = await fetch('https://api.anthropic.com/v1/messages', {
    method:  'POST',
    headers: {
      'x-api-key': process.env.ANTHROPIC_API_KEY,
      'anthropic-version': '2023-06-01',
      'content-type': 'application/json',
    },
    body: JSON.stringify({ model: claudeModel, max_tokens: 4000, system: system || '', messages: cleanMessages, temperature: 0.3 }),
    signal:  AbortSignal.timeout(120000),
  });
  const data = await res.json();
  if (!res.ok || data.type === 'error') throw new Error(data.error?.message || 'AI error');
  return (data.content || []).filter(b => b.type === 'text').map(b => b.text).join('');
}

console.log(`Regenerating cvmaster for: ${slug}`);
generateCvMaster(SCRIPT_DIR, BOT_DIR, slug, ai)
  .then(cv => { console.log('Done:', cv.headline); process.exit(0); })
  .catch(e  => { console.error('Failed:', e.message); process.exit(1); });
