const { missionHelpers, pool } = require('../mariadb');

const missionTitle = 'Vesalius Echo: Theta-92';

const storyFlags = [
  'malachiel_freed',
  'vorn_rescued',
  'safe_prisoners_rescued',
  'tyrant_horror_released',
  'nurgle_lieutenant_revealed',
  'theta92_coordinates_recovered',
  'bile_escape_vector_detected',
  'emergency_resupply_requested'
];

const canon = {
  primaryVillain: 'Fabius Bile',
  chaosTheme: 'Nurgle corruption has infected part of the experiment chain through Apothecary Morbus Threx.',
  nurgleLieutenant: {
    name: 'Apothecary Morbus Threx',
    role: 'Corrupted former Apothecary working under Bile.',
    secret: "He used Nurgle rites and plague-biotech to accelerate Bile's experiments, making them more stable, infectious, and horrifying than normal gene-work should allow.",
    relationshipToBile: 'Bile sees Threx as useful but dangerous. Threx believes decay, disease, and forced adaptation are the true path to perfecting flesh.'
  },
  voidInstabilitySource: {
    source: 'A trapped psyker inside the vault.',
    effect: 'The psyker torment caused void-vox anomalies, unstable reality pockets, equipment disruption, jump pack failures, and displacement incidents.',
    chaosLink: 'The psyker did not intentionally serve Chaos, but the suffering created a breach that Nurgle corruption exploited.'
  },
  nextMissionSeed: {
    title: 'THETA-92: The Infested World',
    hiddenTruth: 'The target planet is Tyranid-infested, and Bile or his agents are experimenting with Tyranid biology under Nurgle-corrupted conditions.',
    opening: 'The Kill-team pursues the escape craft and receives emergency resupply mid-transit or on approach.'
  }
};

const squadTacticsCheck = {
  name: 'Squad Tactics',
  skill: 'Tactics',
  characteristic: 'Int',
  target: 45,
  modifier: 0,
  rulesNote: 'Core: Tactics is an Advanced Intelligence Skill with groups such as Assault Doctrine, Defensive Doctrine, Orbital Drop Procedures, and Recon and Stealth. It gives tactical reading/positioning; it does not grant free Cohesion or Squad Mode abilities.',
  reward: 'On success, the Kill-team identifies the best tactical approach for this scene; extra Degrees of Success may reveal a safer route, priority threat, ambush vector, or better position.',
};

function withSquadTactics(scene) {
  const checks = Array.isArray(scene.checks) ? scene.checks : [];
  if (checks.some(check => String(check.name || '').toLowerCase() === 'squad tactics')) return scene;
  return { ...scene, checks: [squadTacticsCheck, ...checks] };
}

const scenes = [
  {
    title: 'The Living Vault',
    type: 'investigation_rescue',
    mood: 'After the lab fight, the next chamber is not a debrief. It is a living vault, a prison, and a transmitter.',
    description: 'Bag laboratoriets sidste barrikade åbner et rum sig, der ikke føles bygget, men dyrket. Glasbeholdere, stasis-kister og sorte kabler hænger som årer fra loftet. Inde i vaulten bevæger noget sig stadig. Ikke alt er dødt. Ikke alt er menneskeligt. Midt i det hele står Brother Malachiel, fanget i et felt af runer, bio-kabler og psykisk støj.',
    readAloud: 'Bag laboratoriets sidste barrikade åbner et rum sig, der ikke føles bygget, men dyrket. Glasbeholdere, stasis-kister og sorte kabler hænger som årer fra loftet. Inde i vaulten bevæger noget sig stadig. Ikke alt er dødt. Ikke alt er menneskeligt. Midt i det hele står Brother Malachiel, fanget i et felt af runer, bio-kabler og psykisk støj.',
    objectives: [
      'Secure the vault after the laboratory combat.',
      'Free or stabilize Brother Malachiel.',
      'Determine which prisoners are safe and which are latent bio-horrors.',
      'Discover that the vault is also a transmitter.'
    ],
    checks: [
      {
        name: 'Stabilize Malachiel',
        skill: 'Psyniscience',
        characteristic: 'Wp',
        target: 55,
        modifier: 0,
        reward: 'Malachiel is freed without psychic backlash.'
      },
      {
        name: 'Read the prisoners',
        skill: 'Scrutiny',
        characteristic: 'Per',
        target: 45,
        modifier: 0,
        reward: 'The team identifies which prisoners are safe.'
      },
      {
        name: 'Decode vault function',
        skill: 'Tech-Use',
        characteristic: 'Int',
        target: 45,
        modifier: 0,
        reward: 'The team learns the vault is transmitting to THETA-92.'
      }
    ],
    specialPlayerOptions: [
      'The Chaplain may test faith, fear, guilt, or corruption among prisoners.',
      'Malachiel, once freed, may use Librarian senses to detect which captives are warp-tainted.',
      'The Apothecary may identify Nurgle plague-biotech in the sample tissue.',
      'The Techmarine may isolate the vault transmitter.'
    ],
    enemies: [
      {
        name: 'Chaos-Infected Tyrant Horror',
        type: 'nurgle_tyranid_horror',
        count: 1,
        trigger: 'Appears if the team releases prisoners carelessly or fails the corruption check.',
        description: 'A prisoner or sample body erupts into a Tyranid-like horror carrying Nurgle corruption.',
        wounds: 22,
        ws: 45,
        bs: 0,
        ap: 4,
        damage: '1d10+7 R Pen 3 Toxic (1)',
        agBonus: 4,
        fear: 1
      }
    ],
    combat: {
      enemy: 'Chaos-Infected Tyrant Horror',
      weapon: 'Rending talons',
      ws: 45,
      bs: 0,
      modifier: 0,
      damage: '1d10+7',
      targetTB: 4,
      targetArmour: 4,
      mode: 'single',
      rof: 1
    },
    complications: [
      'Failure on Stabilize Malachiel causes psychic feedback and worsens the vault timer.',
      'Failure on Read the prisoners means a prisoner later mutates into a Tyrant Horror.',
      'The trapped psyker is the source of the void-vox anomalies and earlier displacement events.',
      'The psyker is not a willing servant of Chaos, but the suffering created a breach Nurgle corruption exploited.'
    ],
    rewards: { xp: 75, rp: 1 },
    extraChallenges: [
      { id: 'malachiel-clean-freed', text: 'Free Malachiel without severe psychic backlash.', rewardType: 'xp', rewardValue: 75, completed: false },
      { id: 'identify-infected-prisoners', text: 'Correctly identify infected prisoners before releasing them.', rewardType: 'renown', rewardValue: 1, completed: false }
    ],
    storyFlags: ['malachiel_freed', 'tyrant_horror_released', 'theta92_coordinates_recovered'],
    outro: 'Vaultens sidste puls bliver til et koordinatglimt: THETA-92 // ACTIVE // RECEIVING.',
    revealed: false
  },
  {
    title: 'Prisoner Signal',
    type: 'social_horror_choice',
    mood: 'A weak vox-call offers survivors, bait, and a moral cost under a tightening escape timer.',
    description: "Mens vaultens sidste systemer dør, skærer en svag vox-kanal gennem alarmstøjen. Først statisk. Så hosten. Så en stemme. 'Imperial signal... hvis nogen hører dette... vi er stadig i live. Ikke mange. Ikke længe.' Kortet opdaterer: SPECIMEN HOLDING ligger tæt på jeres flugtrute.",
    readAloud: "Mens vaultens sidste systemer dør, skærer en svag vox-kanal gennem alarmstøjen. Først statisk. Så hosten. Så en stemme. 'Imperial signal... hvis nogen hører dette... vi er stadig i live. Ikke mange. Ikke længe.' Kortet opdaterer: SPECIMEN HOLDING ligger tæt på jeres flugtrute.",
    objectives: [
      'Decide whether to spend time rescuing prisoners.',
      'Find Magos-Biologis Ceryx Vorn.',
      'Avoid releasing infected Tyrant Horrors.',
      'Learn that Vesalius was transport, not the source.'
    ],
    checks: [
      {
        name: 'Open specimen holding safely',
        skill: 'Tech-Use',
        characteristic: 'Int',
        target: 45,
        modifier: 0,
        reward: 'The cells open without killing support systems or waking every bio-weapon.'
      },
      {
        name: 'Triage safe prisoners',
        skill: 'Medicae',
        characteristic: 'Int',
        target: 45,
        modifier: 0,
        reward: 'The team identifies which prisoners can be moved and which are contaminated.'
      },
      {
        name: 'Hold prisoner panic under control',
        skill: 'Command',
        characteristic: 'Fel',
        target: 45,
        modifier: 0,
        reward: 'The survivors move fast enough that the escape timer does not worsen.'
      }
    ],
    importantNpc: {
      name: 'Magos-Biologis Ceryx Vorn',
      role: 'Survivor and witness',
      information: [
        'Vesalius was not the source of the experiments.',
        'The ship was transporting refined samples toward THETA-92.',
        'A corrupted Apothecary named Morbus Threx introduced plague-stabilizing agents into the gene-vats.',
        'The Nurgle contamination made the organisms more resilient but less controllable.'
      ]
    },
    enemies: [
      {
        name: 'Chaos-Infected Tyrant Horror',
        type: 'biomorphic_prisoner_trap',
        count: 1,
        wounds: 20,
        ws: 42,
        bs: 0,
        ap: 3,
        damage: '1d10+6 R Pen 3',
        agBonus: 4,
        fear: 1
      }
    ],
    combat: {
      enemy: 'Chaos-Infected Tyrant Horror',
      weapon: 'Bone talons',
      ws: 42,
      bs: 0,
      modifier: 0,
      damage: '1d10+6',
      targetTB: 4,
      targetArmour: 3,
      mode: 'single',
      rof: 1
    },
    complications: [
      'Every extra round spent here tightens the escape timer.',
      'If the biomorphic trap is missed, one prisoner becomes a Fear 1 attacker.',
      "If Vorn survives, he reveals that Bile's work has been altered by Nurgle corruption.",
      'This is a dilemma: saving people costs time, but abandoning Vorn loses the clearest Morbus Threx clue.'
    ],
    rewards: { xp: 100, rp: 1 },
    extraChallenges: [
      { id: 'vorn-rescued', text: 'Extract Magos-Biologis Ceryx Vorn alive.', rewardType: 'xp', rewardValue: 100, completed: false },
      { id: 'safe-prisoners-rescued', text: 'Rescue four or more safe prisoners.', rewardType: 'renown', rewardValue: 1, completed: false }
    ],
    storyFlags: ['vorn_rescued', 'safe_prisoners_rescued', 'nurgle_lieutenant_revealed', 'tyrant_horror_released'],
    outro: 'Vorns stemme er metallisk og ødelagt: "Vesalius var kun transporten. Threx gjorde dem stabile. Bile sendte dem videre."',
    revealed: false
  },
  {
    title: 'Engine Shrine Sabotage',
    type: 'puzzle_combat',
    mood: 'The reactor is protected by living Nurgle-infected growth. Shooting it is not enough. Burning it alone is not enough.',
    description: 'Motorsektionen føles ikke som et maskinrum. Den føles som et kapel bygget af kød og stål. Plasmaledninger hænger som tarme fra loftet. Tre reaktorkerner står i midten, hver omviklet af sortgrønt organisk væv. Når I nærmer jer, åbner vævet små munde og ånder varm, syg damp ud over gulvet.',
    readAloud: 'Motorsektionen føles ikke som et maskinrum. Den føles som et kapel bygget af kød og stål. Plasmaledninger hænger som tarme fra loftet. Tre reaktorkerner står i midten, hver omviklet af sortgrønt organisk væv. Når I nærmer jer, åbner vævet små munde og ånder varm, syg damp ud over gulvet.',
    objectives: [
      'Destroy the engine shrine so Vesalius cannot be repaired.',
      'Solve the Threefold Purge: cold, chemical purge, then fire/plasma.',
      'Plant charges on the exposed reactor cores.',
      'Survive or outrun the defenders released by the shrine.'
    ],
    puzzleName: 'The Threefold Purge',
    puzzleLogic: {
      coreRule: 'The bio-growth must be broken by combining cold, chemical purge, and fire/plasma in the correct sequence.',
      wrongSolutions: [
        'Only shooting the growth causes it to split and regenerate.',
        'Only burning the growth makes it release toxic spores.',
        'Only freezing/cooling it makes it harden around the reactor core.'
      ],
      correctSequence: [
        'Cool the growth using reactor coolant or ruptured coolant lines.',
        'Apply chemical purge from nearby canisters or Mechanicus sterilant tanks.',
        'Burn or overload it with plasma/fire while it is brittle and chemically exposed.'
      ]
    },
    interactiveElements: [
      { name: 'Coolant Line', use: 'Freezes or hardens the growth temporarily.', skill: 'Tech-Use or Strength', target: 40 },
      { name: 'Sterilant Canisters', use: 'Weakens the plague membrane after cooling.', skill: 'Medicae, Tech-Use, or Ballistic Skill to shoot canister accurately', target: 45 },
      { name: 'Plasma Vent', use: 'Burns exposed growth and opens the core for demolition charges.', skill: 'Tech-Use or Demolition', target: 45 }
    ],
    checks: [
      {
        name: 'Rupture or redirect coolant line',
        skill: 'Tech-Use',
        characteristic: 'Int',
        target: 40,
        modifier: 0,
        reward: 'The growth becomes brittle for one round.'
      },
      {
        name: 'Apply sterilant purge',
        skill: 'Medicae',
        characteristic: 'Int',
        target: 45,
        modifier: 0,
        reward: 'The plague membrane weakens after cooling.'
      },
      {
        name: 'Open plasma vent and plant charges',
        skill: 'Demolitions',
        characteristic: 'Int',
        target: 45,
        modifier: 0,
        reward: 'All three charges are planted and Vesalius cannot be repaired.'
      }
    ],
    skillChallenge: {
      goal: '5 successes before 3 failures',
      successResult: 'All three charges are planted and Vesalius cannot be repaired.',
      failureResult: 'The reactor vents plasma: 1d10+4 Energy Pen 3 or lost escape time.',
      at2Failures: 'Two Gland Hounds or Tyrant Horrors enter the shrine.'
    },
    enemies: [
      {
        name: 'Gland Hound',
        type: 'bio-hound',
        count: 2,
        wounds: 18,
        ws: 40,
        bs: 0,
        ap: 2,
        damage: '1d10+5 R Pen 2 Toxic (1)',
        agBonus: 5
      },
      {
        name: 'Chaos-Infected Tyrant Horror',
        type: 'nurgle_tyranid_horror',
        count: 1,
        wounds: 22,
        ws: 45,
        bs: 0,
        ap: 4,
        damage: '1d10+7 R Pen 3 Toxic (1)',
        agBonus: 4,
        fear: 1
      },
      {
        name: 'Nurgle Plague-Servitor',
        type: 'plague_servitor',
        count: 1,
        wounds: 16,
        ws: 35,
        bs: 25,
        ap: 5,
        damage: '1d10+4 I Pen 2 Toxic (1)',
        agBonus: 2,
        optional: true
      }
    ],
    combat: {
      enemy: 'Gland Hound',
      weapon: 'Bite',
      ws: 40,
      bs: 0,
      modifier: 0,
      damage: '1d10+5',
      targetTB: 4,
      targetArmour: 2,
      mode: 'single',
      rof: 1
    },
    complications: [
      'Skill challenge: 5 successes before 3 failures.',
      'Wrong sequence regenerates, spores, or hardens the growth.',
      'Failure causes 1d10+4 Energy Pen 3 or lost escape time.',
      'At 2 failures, two Gland Hounds or Tyrant Horrors enter the shrine.'
    ],
    rewards: { xp: 100, rp: 1 },
    extraChallenges: [
      { id: 'threefold-purge-solved', text: 'Solve the purge puzzle without reaching 3 failures.', rewardType: 'xp', rewardValue: 100, completed: false },
      { id: 'no-escape-delay', text: 'Leave the engine shrine without reducing the escape timer.', rewardType: 'renown', rewardValue: 1, completed: false }
    ],
    storyFlags: ['emergency_resupply_requested'],
    outro: 'Kølingen rammer først. Sterilanten hvæser bagefter. Plasmaen gør resten. Under jer begynder Vesalius at dø.',
    revealed: false
  },
  {
    title: 'The Theta Escape Vector',
    type: 'briefing_hook',
    mood: 'No calm debrief. Vesalius burns behind them while a small craft flees toward THETA-92.',
    description: "Vesalius brænder bag jer, men sejren når aldrig at blive stille. Voxen knitrer fra jeres skib: 'Kill-team, void-augur har kontakt. Lille craft. Ingen imperial ident-kode. Kurs væk fra Vesalius.' Hololithen tegner en tynd rød linje gennem tomrummet mod en nærliggende planet. På skærmen står kun én markør: THETA-92 // ACTIVE // RECEIVING.",
    readAloud: "Vesalius brænder bag jer, men sejren når aldrig at blive stille. Voxen knitrer fra jeres skib: 'Kill-team, void-augur har kontakt. Lille craft. Ingen imperial ident-kode. Kurs væk fra Vesalius.' Hololithen tegner en tynd rød linje gennem tomrummet mod en nærliggende planet. På skærmen står kun én markør: THETA-92 // ACTIVE // RECEIVING.",
    objectives: [
      'Confirm the escape vector.',
      'Choose whether to pursue immediately.',
      'Record what was recovered: Malachiel, prisoners, Vorn, sample data, or corrupted tissue.',
      'Request emergency resupply to be sent after the Kill-team.'
    ],
    checks: [
      {
        name: 'Confirm escape vector',
        skill: 'Awareness',
        characteristic: 'Per',
        target: 45,
        modifier: 10,
        reward: 'The void-augur track confirms a small craft fleeing toward THETA-92.'
      },
      {
        name: 'Lock pursuit solution',
        skill: 'Navigation',
        characteristic: 'Int',
        target: 45,
        modifier: 0,
        reward: 'The Kill-team can pursue immediately without waiting for full command clearance.'
      },
      {
        name: 'Request moving resupply',
        skill: 'Command',
        characteristic: 'Fel',
        target: 45,
        modifier: 10,
        reward: 'A Thunderhawk, drop pod, or support craft is dispatched after them during pursuit.'
      }
    ],
    bileMessageOptional: {
      useIfNeeded: true,
      message: "En forvrænget stemme bryder kort gennem voxen. 'I ødelagde et bur. Ikke dyret. Kom bare efter mig, Astartes. THETA-92 har allerede åbnet sig.'",
      purpose: 'Bile is not just bragging. He is baiting them toward a prepared situation.'
    },
    nextMissionHook: [
      'The planet appears cold, remote, and officially unimportant.',
      'The auspex briefly registers impossible bio-signatures before static kills the feed.',
      'The Kill-team does not yet know the planet is Tyranid-infested.',
      'Command cannot wait for full resupply. A support craft will be dispatched after them.'
    ],
    complications: [
      'Do not run this as a calm debrief.',
      'The stronger hook is the detected escape vector, not a long villain monologue.',
      'Seed Tyranid infestation only as impossible bio-signatures before static kills the feed.',
      'Resupply is not safe at base; it is sent after them while they continue toward the planet.'
    ],
    rewards: { xp: 50, rp: 1 },
    extraChallenges: [
      { id: 'pursuit-priority-recorded', text: 'Choose and record a clear pursuit/intel priority for THETA-92.', rewardType: 'xp', rewardValue: 50, completed: false },
      { id: 'strategic-edge-report', text: 'Frame the report so Deathwatch command gains a strategic edge.', rewardType: 'renown', rewardValue: 1, completed: false }
    ],
    storyFlags: ['theta92_coordinates_recovered', 'bile_escape_vector_detected', 'emergency_resupply_requested'],
    outro: 'Der er ingen tid til hvile. THETA-92 modtager stadig. Et lille fartøj løber foran jer. Resupply må indhente jer under jagten.',
    revealed: false
  }
];

(async function main() {
  const existing = (await missionHelpers.getAll()).find(m => m.name === missionTitle);
  if (!existing) {
    throw new Error(`Mission not found: ${missionTitle}`);
  }

  const ok = await missionHelpers.update(existing.id, {
    name: existing.name,
    theme: 'chaos_biotech_nurgle_theta92',
    sceneCount: scenes.length,
    enemyCount: 4,
    threatLevel: 'High',
    playerCount: existing.player_count || 4,
    scenes: scenes.map(withSquadTactics).map(scene => ({ ...scene, missionCanon: canon, missionStoryFlags: storyFlags }))
  });

  if (!ok) throw new Error(`Failed to update mission ${existing.id}`);

  console.log(JSON.stringify({
    status: 'updated',
    id: existing.id,
    name: existing.name,
    active: existing.is_active,
    sceneCount: scenes.length,
    sceneTitles: scenes.map(scene => scene.title),
    storyFlags
  }, null, 2));

  await new Promise(resolve => setTimeout(resolve, 250));
  await pool.end();
})().catch(async error => {
  console.error(error);
  try { await pool.end(); } catch {}
  process.exit(1);
});
