// fetch is global in Node 18+
import { readFileSync, writeFileSync, readdirSync } from 'fs';
import { join } from 'path';
import { config } from 'dotenv';
import { fileURLToPath } from 'url';
import { dirname } from 'path';

config({ path: join(dirname(fileURLToPath(import.meta.url)), '../.env') });

const BASE = '/home/administrator/vianexu.com/clients/ecobe/admin/src/db/mentees';
const KEY = process.env.ANTHROPIC_API_KEY;

async function generateDesc(cv, cs) {
  const context = [
    cv.headline || '',
    cv.summary || cv.keyNarrative || '',
    `Target: ${(cs.primaryRoles || []).slice(0, 3).join(', ')}`,
    cs.seniority ? `Level: ${cs.seniority}` : '',
  ].filter(Boolean).join('\n');

  const res = await fetch('https://api.anthropic.com/v1/messages', {
    method: 'POST',
    headers: {
      'x-api-key': KEY,
      'anthropic-version': '2023-06-01',
      'content-type': 'application/json',
    },
    body: JSON.stringify({
      model: 'claude-haiku-4-5',
      max_tokens: 80,
      system: 'Write a single concise sentence (max 20 words) describing who this professional is and what they are targeting. No filler, no "currently". Just the essence.',
      messages: [{ role: 'user', content: context }],
    }),
  });
  const data = await res.json();
  return (data.content || []).filter(b => b.type === 'text').map(b => b.text).join('').trim();
}

function reorder(obj, desc) {
  const result = {};
  for (const [k, v] of Object.entries(obj)) {
    if (k === 'shortDescription') continue; // remove from old position
    result[k] = v;
    if (k === 'linkedin') result.shortDescription = desc;
  }
  return result;
}

const slugs = readdirSync(BASE);
for (const slug of slugs) {
  try {
    const csPath = join(BASE, slug, 'career-strategy.json');
    const cvPath = join(BASE, slug, 'cv.json');
    const cs = JSON.parse(readFileSync(csPath, 'utf8'));
    const cv = JSON.parse(readFileSync(cvPath, 'utf8'));
    const desc = await generateDesc(cv, cs);
    writeFileSync(csPath, JSON.stringify(reorder(cs, desc), null, 2));
    console.log(`✓ ${slug}: ${desc}`);
  } catch (e) {
    console.error(`✗ ${slug}: ${e.message}`);
  }
}
