/**
 * groupCvmaster.js — CV Master generation
 *
 * Builds a comprehensive master CV from:
 *   - form.json   (36 onboarding answers)
 *   - career-strategy.json  (coach's strategic positioning)
 *
 * Output saved to mentees/{slug}/cvmaster.json
 */

import { existsSync, readFileSync, writeFileSync } from 'fs';
import { join, dirname } from 'path';
import { fileURLToPath } from 'url';
import { syncWrite } from './sync.js';

async function readPdfText(filePath) {
  if (!existsSync(filePath)) return '';
  try {
    const { PDFParse } = await import('pdf-parse');
    const buffer = readFileSync(filePath);
    const parser = new PDFParse({ data: buffer });
    const result = await parser.getText();
    return (result.text || '').trim();
  } catch (e) {
    console.warn('[cvmaster] could not parse PDF:', e.message);
    return '';
  }
}

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

const CVMASTER_TRAINING = readFileSync(
  join(SCRIPT_DIR, '..', 'training', 'cvmaster.txt'),
  'utf8'
).trim();

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

// ── Loaders ─────────────────────────────────���─────────────────────────��────────

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

// ── Generator ──────────────────────────��──────────────────────────────────────

/**
 * Generate the CV Master document.
 *
 * @param {string} scriptDir - ecobot root dir
 * @param {string} botDir    - bots/BOTID/ dir
 * @param {string} slug      - mentee folder key (e.g. 'john-doe_123')
 * @param {Function} aiFn    - ai(system, messages, model) function
 * @returns {object} cvmaster JSON object
 */
export async function generateCvMaster(scriptDir, botDir, slug, aiFn) {
  const menteeDir = join(scriptDir, 'mentees', slug);

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

  if (!form.answers || Object.keys(form.answers).length === 0) {
    throw new Error(`No form answers found for ${slug}`);
  }

  const cvPersonalText = await readPdfText(join(menteeDir, 'cv-personal.pdf'));
  const cvLinkedinText = await readPdfText(join(menteeDir, 'cv-linkedin.pdf'));

  const inputData = {
    formAnswers:    form.answers,
    careerStrategy: strategy,
    ...(cvPersonalText && { personalCvRawText: cvPersonalText }),
    ...(cvLinkedinText && { linkedinCvRawText: cvLinkedinText }),
  };

  const raw = await aiFn(
    CVMASTER_TRAINING,
    [{ role: 'user', content: JSON.stringify(inputData, null, 2) }],
    'gpt-4.1'  // Use the most capable model for this critical document
  );

  // Parse JSON (strip markdown fences if present)
  let cvmaster;
  try {
    const cleaned = raw.replace(/^```(?:json)?\n?/m, '').replace(/\n?```$/m, '').trim();
    cvmaster = JSON.parse(cleaned);
  } catch (e) {
    throw new Error(`CV Master JSON parse failed: ${e.message}\nRaw: ${raw.slice(0, 200)}`);
  }

  cvmaster.generatedAt = new Date().toISOString();
  cvmaster.slug        = slug;
  cvmaster.leadName    = strategy.leadName || form.answers.full_name || slug;

  // Save locally
  writeFileSync(join(menteeDir, 'cvmaster.json'), JSON.stringify(cvmaster, null, 2));

  // Sync to API
  await syncWrite(botDir, slug, 'cvmaster', cvmaster).catch(e =>
    console.warn('[cvmaster] sync failed:', e.message)
  );

  console.log(`[cvmaster] generated for ${slug}`);

  // Generate full career strategy from form + cvmaster
  try {
    await generateCareerStrategy(menteeDir, botDir, slug, form, cvmaster, strategy, aiFn);
  } catch (e) {
    console.warn('[strategy] generation failed:', e.message);
  }

  return cvmaster;
}

// ── Career Strategy Generator ─────────────────────────────────────────────────

async function generateCareerStrategy(menteeDir, botDir, slug, form, cvmaster, existingStrategy, aiFn) {
  const inputData = {
    formAnswers:      form.answers,
    cvMaster:         cvmaster,
    existingStrategy: existingStrategy,
  };

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

  let strategy;
  try {
    const cleaned = raw.replace(/^```(?:json)?\n?/m, '').replace(/\n?```$/m, '').trim();
    strategy = JSON.parse(cleaned);
  } catch (e) {
    throw new Error(`Strategy JSON parse failed: ${e.message}\nRaw: ${raw.slice(0, 200)}`);
  }

  // Always preserve original 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));

  await syncWrite(botDir, slug, 'career-strategy', strategy).catch(e =>
    console.warn('[strategy] sync failed:', e.message)
  );

  console.log(`[strategy] generated for ${slug}`);
  return strategy;
}

// ── Format for WhatsApp display ───────────────────���────────────────────────────

/**
 * Format a CV Master as a readable WhatsApp message summary.
 */
export function formatCvMasterSummary(cv) {
  const lines = [];

  lines.push(`✅ *Career Plan ready — ${cv.leadName}*\n`);

  if (cv.headline)  lines.push(`📌 *${cv.headline}*`);
  if (cv.summary)   lines.push(`\n${cv.summary}`);

  if (cv.targetRoles?.length) {
    lines.push(`\n🎯 *Target Roles*`);
    cv.targetRoles.forEach(r => lines.push(`  • ${r}`));
  }

  if (cv.targetSectors?.length) {
    lines.push(`\n🏢 *Target Sectors*`);
    cv.targetSectors.forEach(s => lines.push(`  • ${s}`));
  }

  if (cv.salaryTarget) lines.push(`\n💰 *Salary Target:* ${cv.salaryTarget}`);

  if (cv.keyStrengths?.length) {
    lines.push(`\n⚡ *Key Strengths*`);
    cv.keyStrengths.forEach(s => lines.push(`  • ${s}`));
  }

  if (cv.languages?.length) {
    lines.push(`\n🌍 *Languages:* ${cv.languages.map(l => `${l.language} (${l.level})`).join(', ')}`);
  }

  if (cv.mobility) {
    const mob = [];
    if (cv.mobility.openToRemote)   mob.push('Remote ✓');
    if (cv.mobility.openToRelocate) mob.push('Open to relocate ✓');
    if (cv.mobility.workPermits?.length) mob.push(`Permits: ${cv.mobility.workPermits.join(', ')}`);
    if (mob.length) lines.push(`\n🌐 ${mob.join(' | ')}`);
  }

  return lines.join('\n');
}
