/**
 * regenerate-strategy.js
 * Usage: node regenerate-strategy.js <slug>
 * Example: node regenerate-strategy.js tom-smidth_5821622651
 */

import { readFileSync, writeFileSync, existsSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import fetch from 'node-fetch';
import { config } from 'dotenv';

config({ path: new URL('.env', import.meta.url).pathname });

const SCRIPT_DIR = dirname(fileURLToPath(import.meta.url));

const slug = process.argv[2];
if (!slug) { console.error('Usage: node regenerate-strategy.js <slug>'); process.exit(1); }

const menteeDir = join(SCRIPT_DIR, 'mentees', slug);
if (!existsSync(menteeDir)) { console.error(`Mentee not found: ${slug}`); process.exit(1); }

function loadJson(p) {
  if (!existsSync(p)) return {};
  try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return {}; }
}

const STRATEGY_TRAINING = readFileSync(join(SCRIPT_DIR, 'training', 'strategy.txt'), 'utf8').trim();

async function ai(system, messages) {
  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: 'claude-sonnet-4-5', max_tokens: 4000, system: system || '', messages: cleanMessages }),
    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('').trim();
}

const form            = loadJson(join(menteeDir, 'form.json'));
const cvmaster        = loadJson(join(menteeDir, 'cvmaster.json'));
const existingStrategy = loadJson(join(menteeDir, 'career-strategy.json'));

if (!form.answers || Object.keys(form.answers).length === 0) {
  console.error('No form answers found'); process.exit(1);
}
if (!cvmaster.headline) {
  console.error('No cvmaster found — generate cvmaster first'); process.exit(1);
}

console.log(`Generating career strategy for ${slug}...`);

const inputData = { formAnswers: form.answers, cvMaster: cvmaster, existingStrategy };

const raw = await ai(STRATEGY_TRAINING, [{ role: 'user', content: JSON.stringify(inputData, null, 2) }]);

let strategy;
try {
  const cleaned = raw.replace(/^```(?:json)?\n?/m, '').replace(/\n?```$/m, '').trim();
  strategy = JSON.parse(cleaned);
} catch (e) {
  console.error('JSON parse failed:', e.message);
  console.error('Raw output:', raw.slice(0, 500));
  process.exit(1);
}

// Preserve identity fields
strategy.leadId              = existingStrategy.leadId || existingStrategy.id;
strategy.leadName            = existingStrategy.leadName;
strategy.email               = existingStrategy.email || strategy.email;
strategy.createdAt           = existingStrategy.createdAt;
strategy.strategyGeneratedAt = new Date().toISOString();

writeFileSync(join(menteeDir, 'career-strategy.json'), JSON.stringify(strategy, null, 2));
console.log('Done! career-strategy.json updated.');
console.log(`  Segments:  ${strategy.strategy?.segments?.length || 0}`);
console.log(`  Roles:     ${(strategy.primaryRoles || []).join(', ')}`);
console.log(`  Location:  ${strategy.location}`);
console.log(`  Salary:    ${strategy.salaryTarget}`);
