#!/usr/bin/env node
// scripts/gen-stub-transcripts.mjs — writes one stub transcript per lesson
// into data/silver/transcripts/. Skips files that already exist (idempotent).
//
// Each stub is clearly labeled as `[STUB — replace with Whisper transcript
// when video lands]` so the RAG agent can disclaim if it ends up answering
// from a stub. Real Whisper transcripts replace the file with the same name.
//
//   node scripts/gen-stub-transcripts.mjs        # only fill missing
//   node scripts/gen-stub-transcripts.mjs --force # overwrite existing stubs
//
// Linear: ECO-9

import { fileURLToPath } from 'url';
import { dirname, join } from 'path';
import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'fs';

const SCRIPT_DIR = dirname(dirname(fileURLToPath(import.meta.url)));
const TRANSCRIPT_DIR = join(SCRIPT_DIR, 'data', 'silver', 'transcripts');
const force = process.argv.includes('--force');

const STUB_HEADER = '[STUB — replace with Whisper transcript when video lands]';

// Module-specific framing so stubs feel coherent across the 30 days.
const MODULE_INTRO = {
  1: 'Module 1 is about getting clear and getting moving. No overthinking.',
  2: 'Module 2 sharpens the tools — CV, LinkedIn, weekly application rhythm.',
  3: 'Module 3 is about working smarter — better targeting, better outreach, better volume.',
  4: 'Module 4 is the final stretch — interview mastery, negotiation, ownership.',
};

const ACTION_TEMPLATES = [
  (title) => `Action: spend 20–30 minutes on this today. Write your output in your Career Plan or notes file. Reply *Yes* in WhatsApp when done so the bot can send tomorrow's lesson.`,
  (title) => `Action: pick the smallest version of this you can do today (one role, one connection, one application). Done beats perfect. Reply *Yes* when finished.`,
  (title) => `Action: set a 25-minute timer, do the work, and stop. We're optimising for momentum, not depth, in week one.`,
];

const MINDSETS = [
  '"Done is better than perfect. You enter the market this week."',
  '"Speed of execution beats depth of preparation in week one."',
  '"You don\'t need to feel ready. You need to start."',
  '"Volume + reflection + adjustment = offers."',
  '"Momentum compounds. Showing up daily is the strategy."',
];

// Optional per-lesson body hint — if present, used as the middle paragraph.
// This is where richer copy lands when Mads provides scripts later.
const BODY_HINT = {
  L02: 'Pick 2–3 target roles + 2–3 target geographies. Resist the urge to keep options open — focus is what makes applications convert.',
  L03: 'ATS systems parse for structure, keywords, and clean formatting. The CAR method (Context · Action · Result) is how you write bullets a human will actually read.',
  L04: 'Build the first draft in one sitting. You will hate it. That is fine. The first version is just raw material — Day 4 is about getting words on the page.',
  L05: 'LinkedIn baseline: photo, headline that says what you do, About section that maps to your target roles. No fluff, no buzzwords.',
  L06: 'Today is the day you actually apply. 5–10 roles minimum, even if your CV is rough. Real applications produce real feedback.',
  L07: 'You will hit a low this week. Build the habit of breath, mood, and state work now — before you need it for interview pressure.',
  L08: 'Use AI tools to lift your CV from "okay" to "tight". ChatGPT/Claude for rewrites, Jobscan for ATS scoring against specific job descriptions.',
  L09: 'Your CV should pivot per role family. Same content, different framing. Keep a master CV; tailor for each application family.',
  L10: 'Recruiters search LinkedIn by keywords. Reverse-engineer their queries: study 10 job posts in your target role and seed your profile with the words you see repeating.',
  L11: 'Visibility = posting + commenting + connecting. 15 minutes a day, three actions. That is your minimum.',
  L12: 'Treat applications like a system, not a feeling. Weekly target, tracker, retro. Energy follows structure.',
  L13: 'Two-message outreach: short intro + clear ask. Day 1 message, Day 4 follow-up. Cut anything optional.',
  L14: 'Most rejection in week 2 is identity-level. Separate "this application got declined" from "I am unfit". They are not the same statement.',
  L15: 'Use AI to rank job postings against your fit. 30 minutes of triage saves you from chasing 20 wrong roles.',
  L16: 'A wasted application is one to a job you would not actually take. Filter on the front end, not after the offer.',
  L17: 'Skip the gatekeepers. Recruiters move fast; hiring managers care about specific problems. Talk to both, but with different messages.',
  L18: 'Three-touch follow-up cadence: Day 4, Day 10, Day 21. After that, deprioritise. Stale leads cost you energy.',
  L19: 'Connection pyramid: warm > warm-introduced > cold targeted > cold mass. Spend 80% of outreach time at the top of the pyramid.',
  L20: '100 quality applications → 10 conversations → 1 offer is a healthy ratio for week 3+. Adjust if your numbers are wildly off.',
  L21: 'Common questions: "tell me about yourself", "why this role", "tell me about a time you...". Pre-answer these in your own words. Today.',
  L22: 'CV v3 is informed by real feedback from real conversations. Strip what didn\'t land. Sharpen what did.',
  L23: 'Strong answers are specific, brief, and structured. Use the SAR/STAR pattern. Stop talking after the result.',
  L24: 'Confidence is positioning, not bravado. Lower the volume; raise the precision. State your value as a fact, not a sales pitch.',
  L25: 'Negotiate with data and silence. Total comp framework. Ask for time before responding to any offer.',
  L26: 'Articulate your value in one sentence. Then in three. Then in a paragraph. Use whichever fits the moment.',
  L27: 'Week 4 system: same daily rhythm as Week 2, but with sharper targeting and tighter follow-up. Don\'t reinvent — reinforce.',
  L28: 'Network beyond your immediate ask. Ten conversations a week, not for this offer, for the next two roles after.',
  L29: 'You will want to quit somewhere between Day 22 and Day 27. Build the discipline now. Show up anyway.',
  L30: 'You own the system now. Same loop, every week, until you have an offer that fits. Then keep doing it for one more week.',
};

function intro(lesson) {
  const m = lesson.module || 1;
  return `${MODULE_INTRO[m] || ''} Today (Day ${lesson.day}) we focus on: ${lesson.title}.`;
}

function body(lesson) {
  const hint = BODY_HINT[lesson.id];
  if (hint) return hint;
  // Fallback: title-derived sentence so we never ship an empty body.
  return `This lesson covers "${lesson.title}". The recorded video walks through the framework, examples, and the specific exercise to do today. Once the real transcript replaces this stub, the Q&A bot can answer detailed questions from the actual lesson content.`;
}

function action(lesson) {
  return ACTION_TEMPLATES[lesson.day % ACTION_TEMPLATES.length](lesson.title);
}

function mindset(lesson) {
  return MINDSETS[lesson.day % MINDSETS.length];
}

function renderStub(lesson) {
  const lines = [
    STUB_HEADER,
    '',
    `Lesson ${lesson.day} — ${lesson.title}`,
    '',
    intro(lesson),
    '',
    body(lesson),
    '',
    action(lesson),
    '',
    `Mindset: ${mindset(lesson)}`,
    '',
  ];
  if (lesson.weeklyGoalText) {
    lines.push(`Week wrap: ${lesson.weeklyGoalText}`, '');
  }
  return lines.join('\n');
}

function main() {
  mkdirSync(TRANSCRIPT_DIR, { recursive: true });
  const catalog = JSON.parse(readFileSync(join(SCRIPT_DIR, 'data', 'silver', 'lessons.json'), 'utf8'));
  let written = 0, skipped = 0;
  for (const lesson of catalog.lessons) {
    const filename = lesson.transcriptFile || `${lesson.id}.txt`;
    const path = join(TRANSCRIPT_DIR, filename);
    if (existsSync(path) && !force) {
      // Detect existing real transcript: skip; existing stub: also skip unless --force.
      const existing = readFileSync(path, 'utf8');
      const isStub = existing.startsWith(STUB_HEADER);
      if (!isStub) {
        console.log(`SKIP ${filename} (real transcript present)`);
      } else {
        console.log(`SKIP ${filename} (stub already exists; use --force to regenerate)`);
      }
      skipped += 1;
      continue;
    }
    writeFileSync(path, renderStub(lesson));
    console.log(`WRITE ${filename}`);
    written += 1;
  }
  console.log(`\n${written} written, ${skipped} skipped.`);
}

main();
