/**
 * journey.js — Onboarding journey tracker
 *
 * Records every phase transition and significant event for each mentee.
 * Saved to mentees/{slug}/journey.json
 *
 * Structure:
 * {
 *   slug, leadName,
 *   phases: {
 *     waiting:  { startedAt, completedAt },
 *     form:     { startedAt, completedAt, totalAnswers },
 *     cvmaster: { startedAt, completedAt },
 *     active:   { startedAt }
 *   },
 *   events: [{ ts, event, ...data }]
 * }
 */

import { existsSync, readFileSync, writeFileSync } from 'fs';
import { join } from 'path';

// ── Load / Save ───────────────────────────────────────────────────────────────

export function loadJourney(scriptDir, slug) {
  const p = join(scriptDir, 'mentees', slug, 'journey.json');
  if (!existsSync(p)) return { slug, phases: {}, events: [] };
  try { return JSON.parse(readFileSync(p, 'utf8')); }
  catch { return { slug, phases: {}, events: [] }; }
}

export function saveJourney(scriptDir, slug, journey) {
  const p = join(scriptDir, 'mentees', slug, 'journey.json');
  writeFileSync(p, JSON.stringify(journey, null, 2));
}

// ── Helpers ─────────────────────────────────────────────────────────────────���─

function now() { return new Date().toISOString(); }

/**
 * Append an event to the journey log.
 * @param {string} scriptDir
 * @param {string} slug
 * @param {string} event   - event name e.g. 'form_started'
 * @param {object} data    - optional extra fields
 */
export function journeyEvent(scriptDir, slug, event, data = {}) {
  const j = loadJourney(scriptDir, slug);
  j.events = j.events || [];
  j.events.push({ ts: now(), event, ...data });
  saveJourney(scriptDir, slug, j);
}

/**
 * Mark a phase as started.
 */
export function journeyPhaseStart(scriptDir, slug, phase, extra = {}) {
  const j = loadJourney(scriptDir, slug);
  j.phases = j.phases || {};
  j.phases[phase] = { ...(j.phases[phase] || {}), startedAt: now(), ...extra };
  j.events = j.events || [];
  j.events.push({ ts: now(), event: `${phase}_started`, ...extra });
  saveJourney(scriptDir, slug, j);
}

/**
 * Mark a phase as completed.
 */
export function journeyPhaseComplete(scriptDir, slug, phase, extra = {}) {
  const j = loadJourney(scriptDir, slug);
  j.phases = j.phases || {};
  j.phases[phase] = { ...(j.phases[phase] || {}), completedAt: now(), ...extra };
  j.events = j.events || [];
  j.events.push({ ts: now(), event: `${phase}_completed`, ...extra });
  saveJourney(scriptDir, slug, j);
}

/**
 * Record that jobs were sent to the group.
 */
export function journeyJobsSent(scriptDir, slug, count, jobIds = []) {
  journeyEvent(scriptDir, slug, 'jobs_sent', { count, jobIds });
}

/**
 * Record a form answer.
 */
export function journeyFormAnswer(scriptDir, slug, questionKey, index) {
  journeyEvent(scriptDir, slug, 'form_answer', { questionKey, index });
}
